![[译]使用to_dict将pandas.DataFrame转换为Python中的字典列表 [译]使用to_dict将pandas.DataFrame转换为Python中的字典列表](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
pandas.DataFrame.to_json返回的是JSON字符串,不是字典.
可以使用to_dict进行字典转换。
使用orient指定方向。
>>> df
col1 col2
0 1 3
1 2 4
>>> [df.to_dict(orient='index')]
[{0: {'col1': 1, 'col2': 3}, 1: {'col1': 2, 'col2': 4}}]
>>> df.to_dict(orient='records')
[{'col1': 1, 'col2': 3}, {'col1': 2, 'col2': 4}]
原文来源:https://*.com/questions/49027872/convert-pandas-dataframe-to-list-of-dictionaries-in-python