熊猫数据框用于字典,同时保留重复的行

时间:2018-07-09 11:50:49

标签: python pandas dictionary dataframe

我有一个看起来像这样的数据框:

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

我想将其转换成这样的字典中的字典:

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

我能找到的最接近的是以下情况:

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

哪种产量:

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

哪个距离很近但不太远。我真的不知道该怎么办,因此,感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

这对您有用吗?

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

打印(a)

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