You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pandas按Gender分组计算指定多列的均值?

How to Compute Mean of Multiple Columns After Grouping by Gender in Pandas

The Problem Scenario

First, let's recap your dataset and the issue you're facing:

Your raw dataset looks like this:

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

When you ran:

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

You only got the mean for the Age column, but you're expecting the mean values for Age, Salary, and Yr_exp grouped by Gender, like this:

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

The Fix

The issue comes down to how you're selecting multiple columns in pandas. To select multiple columns, you need to pass them as a list inside a second set of square brackets ([['col1', 'col2', 'col3']]), not just a single set.

Here's the corrected code:

# Corrected column selection with double brackets
df.groupby('Gender', as_index=False)[['Age', 'Salary', 'Yr_exp']].mean()

Alternative Approach (Explicit Aggregation)

If you want more control over which aggregation functions apply to which columns, you can use the .agg() method. This is especially useful if you later want to add different functions for different columns:

df.groupby('Gender', as_index=False).agg({
    'Age': 'mean',
    'Salary': 'mean',
    'Yr_exp': 'mean'
})

Why Your Original Code Didn't Work

In pandas, a single set of square brackets with multiple column names (like ['Age', 'Salary', 'Yr_exp']) is not the correct syntax for selecting multiple columns. This syntax can sometimes be misinterpreted (especially in older pandas versions) as trying to access a single column with a tuple name, which leads to unexpected results—like only returning the first column's mean.

Both of the above solutions will give you the exact output you're expecting.


内容的提问来源于stack exchange,提问作者Karma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:57:55