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!
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.