pandas 将数据框转换为字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34329339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert dataframe to dictionary
提问by Sunil Kumar
I intend to get a dictionary with column name as key from a dataframe.
我打算从数据框中获取一个以列名作为键的字典。
Suppose I have a dataframe:
假设我有一个数据框:
a b
0 ac dc
1 ddd fdf
I want the output as:
我希望输出为:
{a : ac, b : dc}
I want it to be done row by row. Any sort of help would be greatly appreciated. Here I want the column name as the key in the resulting dictionary.
我希望它逐行完成。任何形式的帮助将不胜感激。在这里,我希望列名作为结果字典中的键。
回答by mirosval
You can use the to_dict()method with orient='records'
您可以使用该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'}]

