问题
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