Kurosaki Kurosaki - 1 month ago 9
Python Question

How can I add a extra roll of each columns' mean?

When I was using

df['mean'] = df.mean(axis = 1)
, it always added an extra COLUMN of average of each rows. But now I need an extra ROW to get each COLUMNS' mean. So I switch to
df['mean'] = df.mean(axis = 0)
but it still has an extra column but with all NaN. How can I get the row of each columns' average?

Here's the example ↓

example

Answer

IIUC

df = pd.DataFrame(np.arange(16).reshape(-1, 4), list('abcd'), list('ABCD'))

df.loc['mean', :] = df.mean(0)
df.loc[:, 'Mean'] = df.mean(1)
df.loc['mean', 'Mean'] = np.nan

df

enter image description here