我想在数据框中创建一个字典。数据框如下所示:

Vehical | Brand  | Model Name
car     | Suzuki | abc
car     | Honda  | def
bike    | Suzuki | xyz
bike    | Honda  | asd


我希望我的字典像:

{car : {Suzuki : abc, Honda : def}, bike : {Suzuki : xyz, Honda : asd}}

最佳答案

您可以这样操作:

In [29]: df.pivot(index='Vehical', columns='Brand', values='Model Name').to_dict('i')
Out[29]:
{'bike': {'Honda': 'asd', 'Suzuki': 'xyz'},
 'car': {'Honda': 'def', 'Suzuki': 'abc'}}


透视的结果:

In [28]: df.pivot(index='Vehical', columns='Brand', values='Model Name')
Out[28]:
Brand   Honda Suzuki
Vehical
bike      asd    xyz
car       def    abc

10-07 17:02