gpt4 book ai didi

python - 如何将df的每一列转换成字典

转载 作者:行者123 更新时间:2023-11-30 22:06:33 25 4
gpt4 key购买 nike

我想将每一列转换为一个 dictionary ,最后将所有 dictionary 放入 list

import pandas as pd 
df= pd.DataFrame({'city': ['Dubai', 'London', 'San Fransisco'],
'temperature': [33, 12, 18,]})
print(df)

输出:

            city  temperature
0 Dubai 33
1 London 12
2 San Fransisco 18

预期:

mylist = [
{'city': 'Dubai', 'temperature': 33},
{'city': 'London', 'temperature': 12},
{'city': 'San Fransisco', 'temperature': 18},
]

最佳答案

您需要to_dictorient 参数作为 records :

df.to_dict(orient = 'records')

[{'city': 'Dubai', 'temperature': 33},
{'city': 'London', 'temperature': 12},
{'city': 'San Fransisco', 'temperature': 18}]

关于python - 如何将df的每一列转换成字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52686318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com