Python dataframe for dictionary, key issue

I am creating dataframe and then converting to dictionary like 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 value, but somehow I get a strange dictionary

dict_obj
{'B': A
 3    2
 2    5
 1    6
 Name: B, dtype: int64}

      

I want the dictionary object to be

{1:6,2:5,3:2}

      

Can anyone please help?

+3


source to share


1 answer


Use method pd.Series.to_dict



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

{'1': 6, '2': 5, '3': 2}

      

+3


source







All Articles