Menu Close

How to split a Python Pandas dataframe based on groupby?

To split a Python Pandas dataframe based on groupby, we can yuse the groupby method and then call get_group to get data frames from the groups.

For instance, we write

gb = df.groupby('ZZ')    
[gb.get_group(x) for x in gb.groups]

to call groupby to group by the ZZ column.

And then we use list comprehension to call get_group on the gb grouped data frame object with x to return the data frame for each grouped item.

Posted in Python, Python Answers