gpt4 book ai didi

python - Pandas :返回多列的平均值

转载 作者:行者123 更新时间:2023-11-28 20:33:59 24 4
gpt4 key购买 nike

如何输出多列的平均值?

Gender   Age     Salary     Yr_exp   cup_coffee_daily
Male 28 45000.0 6.0 2.0
Female 40 70000.0 15.0 10.0
Female 23 40000.0 1.0 0.0
Male 35 55000.0 12.0 6.0

我有 df.groupby('Gender', as_index=False)['Age', 'Salary', 'Yr_exp'].mean(),但它仍然只返回平均值第一列 Age。如何返回不同列中特定列的平均值?期望的输出:

Gender   Age     Salary   Yr_exp
Male 31.5 50000.0 9.0
Female 31.5 55000.0 8.0

谢谢。

最佳答案

给定这个数据框:

df = pd.DataFrame({
"Gender": ["Male", "Female", "Female", "Male"],
"Age": [28, 40, 23, 35],
"Salary": [45000, 70000, 40000, 55000],
"Yr_exp": [6, 15, 1, 12]
})

df
Age Gender Salary Yr_exp
0 28 Male 45000 6
1 40 Female 70000 15
2 23 Female 40000 1
3 35 Male 55000 12

按性别分组并使用 mean()功能:

df.groupby("Gender").mean()
Age Salary Yr_exp
Gender
Female 31.5 55000.0 8.0
Male 31.5 50000.0 9.0

编辑:您可能需要在 groupby() 之后更改索引方式:df['Age', 'Salary'] 给出一个 KeyError,但 df[['Age', 'Salary']] 返回预期的:

   Age  Salary
0 28 45000
1 40 70000
2 23 40000
3 35 55000

尝试改变

df.groupby("Gender", as_index=True)['Age', 'Salary', 'Yr_exp'].mean() 

df.groupby("Gender", as_index=True)[['Age', 'Salary', 'Yr_exp']].mean()

关于python - Pandas :返回多列的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49560809/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com