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.
JavaScript
x
27
27
1
Sample data:
2
3
print(catStr_df[['Bottle Volume (ml)', 'Pack']][:5])
4
5
Bottle Volume (ml) Pack
6
595 750 12
7
1889 750 12
8
3616 1000 12
9
4422 750 12
10
5022 750 12
11
12
13
Code:
14
15
v = catStr_df[catStr_df['Item Number']==34881][['Bottle Volume (ml)', 'Pack']]
16
.drop_duplicates(keep='first').to_dict()
17
18
v
19
20
Output:
21
22
{'Bottle Volume (ml)': {9534: 1000}, 'Pack': {9534: 12}}
23
24
Desired output:
25
26
{'Bottle Volume (ml)': 1000, 'Pack': 12}
27
Advertisement
Answer
Try adding .to_dict('records')[0]
to the row you want
JavaScript
1
2
1
catStr_df[catStr_df['Item Number']==34881].to_dict('records')[0]
2