将数据帧行转换为dict

use*_*463 7 python dictionary pandas

我有数据框,如下面的示例数据.我正在尝试将数据帧中的一行转换为dict,如下面所需的输出.但是当我使用to_dict时,我得到了indice和列值.有谁知道如何将行转换为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}
Run Code Online (Sandbox Code Playgroud)

小智 12

尝试添加.to_dict('records')[0]到您想要的行

catStr_df[catStr_df['Item Number']==34881].to_dict('records')[0]
Run Code Online (Sandbox Code Playgroud)


Sen*_*rLP 8

用于df.to_dict(orient='index')将索引值作为键,以便于检索数据