Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a pandas DataFrame when using pandas.DataFrame.mean

The function pandas.DataFrame.mean always returns a pandas.Series. I would like it to return a dataframe with the same column names as the original dataframe. How does one do this?

import numpy as np, pandas as pd
df = pd.DataFrame(np.random.rand(10,5), columns = ['a', 'b', 'c', 'd', 'e'])

This returns a pandas.Series object

df.mean()

so does this

df.mean(level = 0)

and so does this

df.mean(axis = 0)

The current way I do this is using the following commands, is this the easiest way to do it?!

means = df.mean(axis = 0)
pd.DataFrame(means).T

I was hoping for a more straight-forward solution!

like image 860
p-robot Avatar asked Dec 19 '22 15:12

p-robot


1 Answers

You could do it like this using to_frame and transpose:

In [188]:
df.mean().to_frame().T

Out[188]:
          a         b         c        d         e
0  0.393221  0.441338  0.445528  0.67516  0.699105
like image 133
EdChum Avatar answered Dec 21 '22 09:12

EdChum