Convert groupby.DataFrameGroupBy object to a dictionary in Python

1k views Asked by At

I have a dataframe as below:

Id | C1 | C2 
---|----|----
 1 | 1  | 12 
 1 | 2  | 15 
 2 | 4  | 20
 2 | 5  | 25

I am trying to groupby 'Id' and construct a dictionary for each 'Id'

df = df.groupby('Id')
dt = df.to_dict()

I get an error:

AttributeError: Cannot access callable attribute 'to_dict' of 'DataFrameGroupBy' objects, try using the 'apply' method

I am trying to get an output(list of dictionaries) as:

{Id: 1: {C1: [1, 2], 
     C2: [12, 15]},

Id: 2: {C1: [4, 5],
     C2: [20, 25]}
}
1

There are 1 answers

4
apatniv On
In [36]: output = {}
In [37]: print(df)
    Id  C1  C2
0   1   1  12
1   1   2  15
2   2   4  20
3   2   5  25

In [38]: columns = set(df.columns.tolist()) - set(['Id'])

In [39]: for key, grouped in df.groupby('Id'):
    ...:     output[key] = {}
    ...:     for col in columns:
    ...:         output[key][col] = grouped[col].tolist()
    ...:         

In [40]: print(output)
{1: {'C2': [12, 15], 'C1': [1, 2]}, 2: {'C2': [20, 25], 'C1': [4, 5]}}