首页 > 解决方案 > 熊猫数据框到具有特定格式的字典

问题描述

我有一个这样的df:

Customer#   Facility   Transp
1           RS         4
2           RS         7
3           RS         9
1           CM         2
2           CM         8
3           CM         5

I want to convert to a dictionary that looks like this:
transp = {'RS' : {1 : 4, 2 : 7, 3 : 9, 
         'CM' : {1 : 2, 2 : 8, 3 : 5}}

我不熟悉这种转换。我尝试了各种选择。数据必须完全采用这种字典格式。我不能用 [] 嵌套。本质上,设施是主要级别,然后是客户/运输。我觉得这应该很容易......谢谢,

标签: pythonpandasdataframedictionarynested

解决方案


您可以一口气完成。

df = pd.DataFrame({"Customer#": [1, 2, 3, 1, 2, 3],
                   "Facility": ['RS', 'RS', 'RS', 'CM', 'CM', 'CM'],
                   "Transp": [4, 7, 9, 2, 8, 5]})

transp = df.groupby('Facility')[['Customer#','Transp']].apply(lambda g: dict(g.values.tolist())).to_dict()

print(transp)

推荐阅读