This question already has answers here:
python pandas dataframe to dictionary
(13个回答)
5年前关闭。
我打算从数据框中获取一个以列名作为键的字典。
假设我有一个数据框:
我希望输出为:
我希望它能逐行完成。任何帮助将不胜感激。
在这里,我希望将列名作为结果字典中的键。
(13个回答)
5年前关闭。
我打算从数据框中获取一个以列名作为键的字典。
假设我有一个数据框:
a b
0 ac dc
1 ddd fdf
我希望输出为:
{a : ac, b : dc}
我希望它能逐行完成。任何帮助将不胜感激。
在这里,我希望将列名作为结果字典中的键。
最佳答案
您可以将 to_dict()
方法与orient='records'
一起使用
import pandas as pd
df = pd.DataFrame([{'a': 'ac', 'b': 'dc'}, {'a': 'ddd', 'b': 'fdf'}])
print(df)
# a b
# 0 ac dc
# 1 ddd fdf
d = df.to_dict(orient='records')
print(d)
# [{'b': 'dc', 'a': 'ac'}, {'b': 'fdf', 'a': 'ddd'}]