You need to enable JavaScript to run this app. Pandas按游戏体裁分组计算user_score均值填充缺失值的实现方法
优惠活动
大模型
产品
解决方案
定价
更多

Pandas按游戏体裁分组计算user_score均值填充缺失值的实现方法

核心问题根因定位
  • 第一个异常(分组计算均值全为NaN)的根源:replace语句的逻辑错误
    你写的games['user_score'] = games['user_score'].replace('tbd', np.nan, inplace=True)存在双重逻辑问题:设置inplace=True时,replace方法会就地修改原DataFrame,自身返回None。把None赋值回games['user_score'],直接把整列内容覆盖为空值,后续所有类型转换、分组计算都是基于全空的列操作,自然所有分组均值都是NaN。
  • 第二个异常(换用.nanmean()报错)的根源:是上述赋值错误的连锁反应。整列被覆盖为全空对象后,传入apply的分组子序列已经不是合法的数值型Series,调用任何数值计算方法都会触发类型错误,和.nanmean()本身的逻辑无关。
正确实现代码(全流程可跑通)
  • 第一步:清洗列内容,替换标记值并转换类型
    import pandas as pd
    import numpy as np
    # 正确替换'tbd'为NaN:不添加冗余的inplace参数,直接接收返回的修改后序列
    games['user_score'] = games['user_score'].replace('tbd', np.nan)
    # 转换为浮点类型
    games['user_score'] = games['user_score'].astype(float)
    
  • 第二步:按体裁分组完成缺失值填充
    优先用transform替代裸apply,保证返回序列和原表索引完全对齐,避免分组后的索引错位问题:
    # 计算组内非空均值填充同组缺失值,Series的mean()方法会自动跳过NaN值,无需额外调用nanmean
    games['user_score'] = games.groupby('genre', sort=False)['user_score'].transform(
        lambda x: x.fillna(x.mean())
    )
    
  • 可选兜底逻辑:如果某个genre分组下所有值都是NaN,组内均值自然是NaN,此时可以用全局用户得分均值对这类分组的剩余缺失值做兜底填充:
    global_mean_score = games['user_score'].mean()
    games['user_score'] = games['user_score'].fillna(global_mean_score)
    
  • 第三步:验证结果
    print(games.groupby('genre')['user_score'].mean())
    print(games['user_score'].head(10))
    
常见误区提醒
  • 不需要刻意在分组计算中调用np.nanmean():pandas的Series内置mean()方法默认就会忽略空值,计算效果和np.nanmean()完全一致;如果确实要调用,写法为lambda x: x.fillna(np.nanmean(x)),前提是分组序列不是全空的合法数值列。
  • 尽量避免在有返回值的pandas方法中同时使用inplace=True和二次赋值,这类写法很容易把整列覆盖为None,是pandas新手的高频踩坑点。

内容的提问来源于stack exchange,提问作者lm.bertrand

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.26 10:36:04