Python 将数据帧转换为具有特定格式的字典

Python 将数据帧转换为具有特定格式的字典,python,pandas,dataframe,dictionary,nested,Python,Pandas,Dataframe,Dictionary,Nested,我有这样一个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: tra

我有这样一个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}}

我不熟悉这种转换。我尝试了各种选择。数据必须完全采用此字典格式。我不能和[]筑巢。基本上,设施是第一级,然后是客户/运输。我觉得这应该很容易。。。。谢谢,

你可以一次完成

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)

欢迎来到堆栈溢出!