I'm trying to group a pandas dataframe by a column and then also calculate the mean for multiple columns. In the sample below I would like to group by the 'category' column and then calculate the mean for the 'score' and 'priority' columns. All three columns should be in the resulting dataframe.
I am able to group and calculate the mean for the first column but I don't know how to add the second column. Below my attempt.
Any guidance greatly appreciated.
import pandas as pd
data = [['A', 2, 1], ['A', 4, 2], ['B', 5, 3], ['B', 2, 3]]
df = pd.DataFrame(data, columns=['category', 'score', 'priority'])
print(df)
# This fails:
results_df = df.groupby('category')['score'].agg(['mean',])['priority'].agg(['mean',])
print(results_df)
CodePudding user response:
df.groupby("category", as_index=False).mean()
CodePudding user response:
df.groupby("category").mean()