[英]convert a dataframe into dictionary - 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')
并且没有任何意义。
你会怎么做?
使用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]}}]
行上的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]}}]
'''
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.