Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python dataframe to dictionary, key value issue

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?

like image 291
Manoj Agrawal Avatar asked Jul 16 '26 15:07

Manoj Agrawal


1 Answers

Use the pd.Series.to_dict method

frame.groupby('A').B.median().to_dict()

{'1': 6, '2': 5, '3': 2}
like image 186
piRSquared Avatar answered Jul 18 '26 04:07

piRSquared