'Pandas DataFrame splitting with multiple attributes

If I had a pandas data frame with columns x , y , h , w and label.

For example:

x  y  h  w  label
0  0  4  4  1
4  0  4  8  1
0  4  8  4  2
8  0  4  4  3
8  8  4  8  2

Is there any way to split them into groups with same h and w values?

Into following

Group 1

x  y  h  w  label
0  0  4  4  1
8  0  4  4  3

Group 2

x  y  h  w  label
4  0  4  8  1
8  8  4  8  2

Group3

x  y  h  w  label
0  4  8  4  2


Solution 1:[1]

Use DataFrame.groupby + dict comprehension to get a dict of DataFrame, you could create new variables with globals() but it is not recommended

dict_dfs = {i:group for i, group in df.groupby(['h', 'w'])}

Or

dict_dfs = {f'Group {i}' : group 
            for i, (_, group) in enumerate(df.groupby(['h', 'w']), 1)}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1