How to convert pandas dataframe to nested dictionary

前端 未结 2 980
渐次进展
渐次进展 2021-01-17 20:04

I am running Python 3.6 and Pandas 0.19.2 and have a DataFrame which looks as follows:

Name      Chain        Food       Healthy  

George    McDonalds    b         


        
相关标签:
2条回答
  • 2021-01-17 20:14

    Solution using dictionary comprehension and groupby:

    {n: grp.loc[n].to_dict('index')
     for n, grp in df.set_index(['Name', 'Chain']).groupby(level='Name')}
    
    {'George': {'KFC': {'Food': 'chicken', 'Healthy': False},
      'McDonalds': {'Food': 'burger', 'Healthy': False}},
     'John': {'McDonalds': {'Food': 'salad', 'Healthy': True},
      'Wendys': {'Food': 'burger', 'Healthy': False}}}
    

    Solution using defaultdict:

    from collections import defaultdict
    
    d = defaultdict(dict)
    
    for i, row in df.iterrows():
        d[row.Name][row.Chain] = row.drop(['Name', 'Chain']).to_dict()
    
    dict(d)
    
    {'George': {'KFC': {'Food': 'chicken', 'Healthy': False},
      'McDonalds': {'Food': 'burger', 'Healthy': False}},
     'John': {'McDonalds': {'Food': 'salad', 'Healthy': True},
      'Wendys': {'Food': 'burger', 'Healthy': False}}}
    
    0 讨论(0)
  • 2021-01-17 20:26

    I think you was very close.

    Use groupby and to_dict:

    df = df.groupby('Name')[['Chain','Food','Healthy']]
           .apply(lambda x: x.set_index('Chain').to_dict(orient='index'))
           .to_dict()
    
    print (df)
    {'George': {'KFC': {'Healthy': False, 'Food': 'chicken'}, 
               'McDonalds': {'Healthy': False, 'Food': 'burger'}}, 
    'John': {'McDonalds': {'Healthy': True, 'Food': 'salad'},
             'Wendys': {'Healthy': False, 'Food': 'burger'}}}
    
    0 讨论(0)
提交回复
热议问题