I am creating a dataframe and then converting to a dictionary as below
data = {'ID': [1,2,3,4,5],
'A':['1','2','1','3','2'],
'B':[4,6,8,2,4]}
frame = pd.DataFrame(data)
dict_obj = dict(frame[['A','B']].groupby('A').median().sort_values(by='B'))
My problem is that I want column A as Key and column B as values but somehow I am getting a weird dictionary
dict_obj
{'B': A
3 2
2 5
1 6
Name: B, dtype: int64}
i want dictionary object as
{1:6,2:5,3:2}
Could someone help please?
Use the pd.Series.to_dict method
frame.groupby('A').B.median().to_dict()
{'1': 6, '2': 5, '3': 2}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With