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 10111213
a 891011
b 12131415
foo AVG 2345
a 0123
b 4567
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]:
metric1metric2RPRPindexindex2fooa0123b4567AVG2345bara891011b12131415AVG10111213
Post a Comment for "Append Rows To A Pandas Groupby Object"