如何用Pandas按Gender分组计算指定多列的均值?
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

