将数据框转换为字典 [英] Convert dataframe to dictionary
本文介绍了将数据框转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我打算从数据框中获取一个带有列名称的字典。
I intend to get a dictionary with column name as key from a dataframe.
假设我有一个数据框:
a b
0 ac dc
1 ddd fdf
我希望输出为:
{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.
推荐答案
您可以使用 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'}]
这篇关于将数据框转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文