Skip to content Skip to sidebar Skip to footer

Append Rows To A Pandas Groupby Object

I am trying to figure out the best way to insert the means back into a multi-indexed pandas dataframe. Suppose I have a dataframe like this: metric 1 metric 2

Solution 1:

The main thing you need to do here is append your means to the main dataset. The main trick you need before doing that is just to conform the indexes (with the reset_index() and set_index() so that after you append them they will be more or less lined up and ready to sort based on the same keys.

In [35]: df2 = df.groupby(level=0).mean()

In [36]: df2['index2'] = 'AVG'

In [37]: df2 = df2.reset_index().set_index(['index','index2']).append(df).sort()

In [38]: df2
Out[38]: 
             metric 1     metric 2    
                    R   P        R   P
index index2                          
bar   AVG          10  11       12  13
      a             8   9       10  11
      b            12  13       14  15
foo   AVG           2   3        4   5
      a             0   1        2   3
      b             4   5        6   7

As far as ordering the rows, the best thing is probably just to set the names so that sorting puts them in the right place (e.g. A,B,avg). Or for a small number of rows you could just use fancy indexing:

In [39]: df2.ix[[4,5,3,1,2,0]]
Out[39]: 
             metric 1     metric 2    
                    R   P        R   P
index index2                          
foo   a             0   1        2   3
      b             4   5        6   7
      AVG           2   3        4   5
bar   a             8   9       10  11
      b            12  13       14  15
      AVG          10  11       12  13

Post a Comment for "Append Rows To A Pandas Groupby Object"