简体   繁体   中英

How to convert pandas dataframe to datadict

I have the following pandas dataframe. I wish to convert to a default or datadict.

Dataframe:

    Col A    Col B   Col C
 0   a1     k1       v1  
 1   a1     k2       v2  
 2   a1     k3       v3  
 3   a2     k4       v4  
 4   a3     k5       v5  
 5   a3     k6       v6  

Output expected:

# dict
{
    "a1" : {"k1": "v1", k2: "v2", "k3": "v3"},
    "a2" : {"k4": "v4"},
    "a3" : {"k5": "v5", "k6": "v6"}
}

I tried this with no luck.

dict = df.set_index('Col A').groupby('Col B').apply( lambda x: x.ColC.to_dict()).to_dict()

Thanks for the help!!

Using groupby with to_dict

{x : y.set_index('ColB')['ColC'].to_dict()for x, y in  df.groupby('ColA')}
Out[252]: 
{'a1': {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'},
 'a2': {'k4': 'v4'},
 'a3': {'k5': 'v5', 'k6': 'v6'}}

Use groupby and iterate over your groups:

{k: dict(g[['Col B', 'Col C']].values) for k, g in df.groupby('Col A')}

{'a1': {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'},
 'a2': {'k4': 'v4'},
 'a3': {'k5': 'v5', 'k6': 'v6'}}

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