Home > Net >  Finding .mean() of all columns in python using loop
Finding .mean() of all columns in python using loop

Time:12-06

I have the following dataframe: Dataframe

Now i want to find the average of every column and create a new dataframe with the result.

My only solution has been:

#convert all rows to mean of values in column
df_find_mean['Germany'] = (df_find_mean["Germany"].mean())

df_find_mean['Turkey'] = (df_find_mean["Turkey"].mean())

df_find_mean['USA_NJ'] = (df_find_mean["USA_NJ"].mean())

df_find_mean['USA_TX'] = (df_find_mean["USA_TX"].mean())

df_find_mean['France'] = (df_find_mean["France"].mean())

df_find_mean['Sweden'] = (df_find_mean["Sweden"].mean())

df_find_mean['Italy'] = (df_find_mean["Italy"].mean())

df_find_mean['SouthAfrica'] = (df_find_mean["SouthAfrica"].mean())

df_find_mean['Taiwan'] = (df_find_mean["Taiwan"].mean())

df_find_mean['Hungary'] = (df_find_mean["Hungary"].mean())

df_find_mean['Portugal'] = (df_find_mean["Portugal"].mean())

df_find_mean['Croatia'] = (df_find_mean["Croatia"].mean())

df_find_mean['Albania'] = (df_find_mean["Albania"].mean())

df_find_mean['England'] = (df_find_mean["England"].mean())

df_find_mean['Switzerland'] = (df_find_mean["Switzerland"].mean())

df_find_mean['Denmark'] = (df_find_mean["Denmark"].mean())

#Remove all rows except first
df_find_mean = df_find_mean.loc[[0]]

#Verify data
display(df_find_mean)

Which works, but is not very elegant. Is there some way to iterate over each column and construct a new dataframe as the average (.mean()) of that colume?

Expected output: Dataframe with average of columns from previous dataframes

CodePudding user response:

Use DataFrame.mean with convert Series to one row DataFrame by Series.to_frame and transpose:

df = df_find_mean.mean().to_frame().T
display(df)

CodePudding user response:

Just use DataFrame.mean() to compute the mean of all your columns:

You can compute the mean of each column by df_find_mean.mean() and then integrate this into pd.DataFrame([df_find_mean.mean()])!

means = df_find_mean.mean()
df_mean = pd.DataFrame([means])

display(df_mean)
  • Related