简体   繁体   中英

Pandas dataframe to dictionary with specific format

I have a df like this:

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

I'm unfamiliar with this conversion. I tried various options. The data has to be exactly in this dictionary format. I can't have nesting with []. Essentially Facility is the primary level then Customer / Transp. I feel like this should be easy.... Thanks,

You can do it in one go.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM