Python 将数据帧复制到dict,同时保留重复的行

Python 将数据帧复制到dict,同时保留重复的行,python,pandas,dictionary,dataframe,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'}} 我想把它转换成这样一本字典中的字典: kenteken status code

我有一个如下所示的数据帧:

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'}}
我想把它转换成这样一本字典中的字典:

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'}}}

这很接近,但不完全相同。我真的不知道该怎么办了,谢谢你的帮助

这对你有用吗

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

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

它必须是一本字典吗?看看OrderedDict。也许一个元组列表就足以满足您的需要。我不认为它足以满足后面的步骤,但我会尝试一下**谢谢!df.to_dictorient=记录让您接近。字典不能有多个值的键映射,这看起来像您想要的。但是,您可以有一个包含多个值的元组的键。这样行吗?例如{'XYZ':{'code':'123','status':'A'},{'code':'456','status':'B'}太棒了!非常感谢:Dglad,这很有帮助。顺便说一句,你也可以投票回答:我试过了,但我的代表太低了,所以它不会明显可见,但仍然很重要;