Pandas add Mean column header

Viewed 458

I'm trying to add column header for a mean column. Refer to below Mean for each column in df :

    A   B   C
0   5   3   8
1   5   3   9
2   8   4   9

df.mean()

A    6.000000
B    3.333333
C    8.666667
dtype: float64

What I want to achieve is below output:

     Mean
A    6.000000
B    3.333333
C    8.666667
dtype: float64

So far I've tried df.columns['Mean'] but does not work. I think it's something to do with the dtype float64 instead of standard dataframe object. Can anyone give a hint.

2 Answers

You can rename the series and use series.to_frame()

df.mean().rename('Mean').to_frame()

Or as suggested by @user3483203, to_frame() accepts a name parameter too:

df.mean().to_frame('Mean')

       Mean
A  6.000000
B  3.333333
C  8.666667

@anky answer is the way to go. This is just a different way to show the way using agg :)

df.agg(['mean']).T

Out[493]:
       mean
A  6.000000
B  3.333333
C  8.666667
Related