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
R P R P
foo a 0 1 2 3
b 4 5 6 7
bar a 8 9 10 11
b 12 13 14 15
I would like to get the following result:
metric 1 metric 2
R P R P
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
Please note, I know I can do df.mean(level=0)
to get the level 0 group means as a separate dataframe. This is not exactly what I want -- I want to insert the group means as rows back into the group.
I am able to get the result I want, but I feel like I am doing this wrong/there is probably a one liner that I am missing that already does this without the expensive python iteration. Here is my example code:
import numpy as np
import pandas as pd
data = np.arange(16).reshape(4,4)
row_index = [("foo", "a"), ("foo", "b"), ("bar", "a"), ("bar", "b")]
col_index = [("metric 1", "R"), ("metric 1", "P"), ("metric 2", "R"),
("metric 2", "P")]
col_multiindex = pd.MultiIndex.from_tuples(col_index)
df = pd.DataFrame(data, index=pd.MultiIndex.from_tuples(row_index),
columns=col_multiindex)
new_row_index = []
data = []
for name, group in df.groupby(level=0):
for index_tuple, row in group.iterrows():
new_row_index.append(index_tuple)
data.append(row.tolist())
new_row_index.append((name, "AVG"))
data.append(group.mean().tolist())
print pd.DataFrame(data,
index=pd.MultiIndex.from_tuples(new_row_index),
columns=col_multiindex)
Which results in:
metric 1 metric 2
R P R P
bar a 8 9 10 11
b 12 13 14 15
AVG 10 11 12 13
foo a 0 1 2 3
b 4 5 6 7
AVG 2 3 4 5
which flips the order of the groups for some reason, but is more or less what I want.
Use DataFrame.append() method to concatenate DataFrames on rows. For E.x, df. append(df1) appends df1 to the df DataFrame.
You can group DataFrame rows into a list by using pandas. DataFrame. groupby() function on the column of interest, select the column you want as a list from group and then use Series. apply(list) to get the list for every group.
Use concat() to Append Use pd. concat([new_row,df. loc[:]]). reset_index(drop=True) to append the row to the first position of the DataFrame as Index starts from zero.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With