pandas 将数据帧行转换为字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50575802/
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 row to dict
提问by user3476463
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.
我有像下面的示例数据一样的数据帧。我正在尝试将数据框中的一行转换为像下面所需的输出那样的字典。但是当我使用 to_dict 时,我会得到索引和列值。有谁知道如何将行转换为像所需输出那样的字典?非常感谢任何提示。
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}
回答by nimrodz
Try adding .to_dict('records')[0]
to the row you want
尝试添加.to_dict('records')[0]
到您想要的行
catStr_df[catStr_df['Item Number']==34881].to_dict('records')[0]