Mean of each column of multiple dataframes to a dataframe - Python pandas

Viewed 1801

I have a dataframe df as follows:

A  B  C
1  2  3
2  1  2 
3  3  1 

And I would like the mean of every column and make a dataframe with it. That would be in this example:

A B C
2 2 2

The code I did was:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10, 3), columns=list('ABC')) # To create df
dfs = np.array_split(df.sample(frac=1),4) # Split it in 4
daf = []
for i in range(len(dfs):
   daf.append(dfs[i].mean())
daf.to_frame()

However I am unable to make it work.

2 Answers

Use mean, but because it return Series use to_frame and transpose:

df = df.mean().to_frame().T
print (df)
     A    B    C
0  2.0  2.0  2.0

Or:

df = pd.DataFrame([df.mean()])
print (df)
     A    B    C
0  2.0  2.0  2.0

For multiple DataFrames:

daf = []
for i in dfs:
   daf.append(i.mean().to_frame().T)

print (daf[0])
         A         B        C
0 -0.92493  1.022305  1.52295

what is same as list comprehension solution:

daf = [i.mean().to_frame().T for i in dfs]

the method of dataframe, 'apply' will be good. the code is below.

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10, 3), columns=list('ABC')) # To create df
df.apply(lambda x: np.mean(x), axis=0)
Related