pandas MultiIndex Iterate over DataFrame with MultiIndex


Example

Given the following DataFrame:

In [11]: df = pd.DataFrame({'a':[1,1,1,2,2,3],'b':[4,4,5,5,6,7,],'c':[10,11,12,13,14,15]})

In [12]: df.set_index(['a','b'], inplace=True)

In [13]: df
Out[13]: 
      c
a b    
1 4  10
  4  11
  5  12
2 5  13
  6  14
3 7  15

You can iterate by any level of the MultiIndex. For example, level=0 (you can also select the level by name e.g. level='a'):

In[21]: for idx, data in df.groupby(level=0):
            print('---')
            print(data)
---
      c
a b    
1 4  10
  4  11
  5  12
---
      c
a b    
2 5  13
  6  14
---
      c
a b    
3 7  15

You can also select the levels by name e.g. `level='b':

In[22]: for idx, data in df.groupby(level='b'):
            print('---')
            print(data)
---     
      c
a b    
1 4  10
  4  11
---
      c
a b    
1 5  12
2 5  13
---
      c
a b    
2 6  14
---
      c
a b    
3 7  15