Looping over groups in a grouped dataframe

df.groupby returns an iterable of 2-tuples: the index, and the group. You can iterate over each group like this:

for _, g in frame.groupby(frame.index):
    .... # do something with `g`

However, if you want to perform some operation on the groups, there are probably better ways than iteration.


Here is an example:

groups = frame.groupby(level=0)

for n,g in groups:
    print('This is group '+ str(n)+'.')
    print(g)
    print('\n')

Output:

This is group A.
   X  Y   Z
A  1  6  11
A  2  7  12
A  3  8  13


This is group B.
   X   Y   Z
B  4   9  14
B  5  10  15