将dataframe行转换为dict [英] convert dataframe row to dict
本文介绍了将dataframe行转换为dict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的数据框像下面的示例数据一样.我正在尝试将数据帧中的一行转换为像下面所需输出那样的字典.但是,当我使用to_dict时,会得到索引以及列值.有谁知道如何将行转换为像期望的输出一样的字典?任何提示,不胜感激.
I have datarame like the sample data below. I'm trying to convert one row from the dataframe in to a dict like the desired output below. But when I use to_dict I get the indice along with the column value. Does anyone know how to get convert the row to a dict like the desired output? Any tips greatly appreciated.
Sample data:
print(catStr_df[['Bottle Volume (ml)', 'Pack']][:5])
Bottle Volume (ml) Pack
595 750 12
1889 750 12
3616 1000 12
4422 750 12
5022 750 12
Code:
v = catStr_df[catStr_df['Item Number']==34881][['Bottle Volume (ml)', 'Pack']]\
.drop_duplicates(keep='first').to_dict()
v
Output:
{'Bottle Volume (ml)': {9534: 1000}, 'Pack': {9534: 12}}
Desired output:
{'Bottle Volume (ml)': 1000, 'Pack': 12}
推荐答案
尝试将.to_dict('records')[0]
添加到所需行中
catStr_df[catStr_df['Item Number']==34881].to_dict('records')[0]
这篇关于将dataframe行转换为dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文