If I have a Dataframe and I'd like to insert a summary column at the beginning I can run
df.insert(0, 'Average', df.mean(axis='columns'))
Say I have a MultiIndexed dataframe of the form
df = pd.DataFrame()
for l1 in ('a', 'b'):
for l2 in ('one', 'two'):
df[l1, l2] = np.random.random(size=5)
df.columns = pd.MultiIndex.from_tuples(df.columns, names=['L1', 'L2'])
L1 a b
L2 one two one two
0 0.585409 0.563870 0.535770 0.868020
1 0.404546 0.102884 0.254945 0.362751
2 0.475362 0.601632 0.476761 0.665126
3 0.926288 0.615655 0.257977 0.668778
4 0.509069 0.706685 0.355842 0.891862
How do I add the mean of all the one
columns and all the two
columns to the first two columns of this DataFrame and call it 'Average'
?
EDIT:
Expected output would be df.mean(level=1, axis=1)
but inserted into the first two columns of the frame with the L1 label 'Average'
. I was hoping the following would work:
df.insert(0, 'Average', df.mean(level=1, axis=1))