将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]