How to convert pandas dataframe to datadict

3162 views python
-2

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

answered question

2 Answers

2

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

posted this
3

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

posted this

Have an answer?

JD

Please login first before posting an answer.