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

pandas按性别分组后新增1-8岁年龄列统计对应人数的实现问题

解决方案

你当前得到的df_age为长结构数据,只需做透视转宽表后和df_temp按sex索引合并即可,完整实现代码如下:

import seaborn as sns
import numpy as np
import pandas as pd

# 导入数据集
df = sns.load_dataset('titanic')
age_buckets = range(1,9)

# 计算分性别fare均值
df_temp = df.groupby('sex').agg({'fare':np.mean})

# 生成分性别分年龄人数统计,转宽表
df_age = df[df.age.isin(age_buckets)].groupby(['sex','age'])['survived'].count().reset_index()
df_age_wide = df_age.pivot(index='sex', columns='age', values='survived') \
                    .add_prefix('age_') \
                    # 确保1-8岁列全部存在,无数据补0
                    .reindex([f'age_{i}' for i in age_buckets], axis=1, fill_value=0) \
                    .astype(int)

# 合并得到最终表
result = df_temp.join(df_age_wide).reset_index()

执行后result的结构和你要求的目标表完全一致,无对应乘客的年龄计数会自动填充为0,不需要保留索引的话reset_index()执行后sex会自动转为普通列。


内容的提问来源于stack exchange,提问作者Jonas Palačionis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 12:06:04