Pandas dataframe to dict, while keeping duplicate rows

一笑奈何 提交于 2021-02-19 07:02:47

问题


I have a dataframe that looks like this:

kenteken status code
0      XYZ      A  123
1      XYZ      B  456
2      ABC      C  789

And I want to convert it to a dictionary in a dictionary like this:

{'XYZ':{'code':'123', 'status':'A'}, {'code':'456', 'status':'B'}, 'ABC' : {'code':'789', 'status:'C'}}

The closest I've been able to come was the folling:

df.groupby('kenteken')['status', 'code'].apply(lambda x: x.to_dict()).to_dict()

Which yields:

{'ABC': {'status': {2: 'C'}, 'code': {2: '789'}},'XYZ': {'status': {0: 'A', 1: 'B'}, 'code': {0: '123', 1: '456'}}}

Which is close but not quite. I really don't know what to do anymore, so appreciate any help!


回答1:


Does this work for you?

a = dict(df.set_index('kenteken').groupby(level = 0).\
    apply(lambda x : x.to_dict(orient= 'records')))

print(a)

{'ABC': [{'status': 'C', 'code': 789}], 'XYZ': [{'status': 'A', 'code': 123}, {'status': 'B', 'code': 456}]}


来源:https://stackoverflow.com/questions/51244920/pandas-dataframe-to-dict-while-keeping-duplicate-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!