将数据帧转换为python字典

2024-06-28 23:44:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个csv文件,如下所示:

Country/Region  1/22/20     1/23/20     1/24/20
Afghanistan     100         200          300
Albania         400         500           0
Algeria          20          30           70    

(该表显示了特定日期和国家的案例数量)

我想将其转换为以下格式的词典:

{
"Country1": {"time": [1/22/20, 1/23/20,...], "cases": [0, 0,...],
"Country2": {"time": [1/22/20, 1/23/20,...], "cases": [0, 0,...],
...
}

通过使用to_dict('records') 看起来非常相似,但不一样

[{'Country/Region': 'Afghanistan', '1/22/20': 0, '1/23/20': 0, '1/24/20': 0,...}]

我一直在尝试使用groupby('Country/Region') ,但毫无意义

你会怎么做


Tags: 文件csv数量time格式国家countryregion
2条回答

行上的apply()就足够了

df.set_index('Country/Region').apply(lambda row: {row.name: {"time": row.index.tolist(), "cases": row.tolist()}}, axis=1).tolist()

'''
[{'Afghanistan': {'time': ['1/22/20', '1/23/20', '1/24/20'], 'cases': [100, 200, 300]}},
 {'Albania': {'time': ['1/22/20', '1/23/20', '1/24/20'], 'cases': [400, 500, 0]}},
 {'Algeria': {'time': ['1/22/20', '1/23/20', '1/24/20'], 'cases': [20, 30, 70]}}]
'''

使用List Comprehension

In [2017]: d = [{c: {'time': d.columns.tolist(), 'cases': d.values.tolist()[0]}} for c, d in df.set_index(['Country/Region']).groupby('Country/Region')]

In [2018]: d
Out[2018]: 
[{'Afghanistan': {'time': ['1/22/20', '1/23/20', '1/24/20'],
   'cases': [100, 200, 300]}},
 {'Albania': {'time': ['1/22/20', '1/23/20', '1/24/20'],
   'cases': [400, 500, 0]}},
 {'Algeria': {'time': ['1/22/20', '1/23/20', '1/24/20'],
   'cases': [20, 30, 70]}}]

相关问题 更多 >