3

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.

0

2 Answers 2

4

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]
Sign up to request clarification or add additional context in comments.

1 Comment

If it is multiple dataframes, how can I do it?
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.