Kurosaki Kurosaki - 9 months ago 40
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 ↓


Answer Source


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


enter image description here