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

为何在该DataFrame中使用GroupBy求均值时报TypeError?如何解决

修复df11.groupby("Type 2").mean()触发的TypeError错误

问题场景

我基于主Pokemon DataFrame创建了df11:

df11= df.drop(["Name", "#"], axis=1).head(9)

得到的df11数据如下:

Type 1  Type 2  HP  Attack  Defense Sp. Atk Sp. Def Speed   Generation  Legendary
0   Grass   Poison  45  49  49  65  65  45  1   False
1   Grass   Poison  60  62  63  80  80  60  1   False
2   Grass   Poison  80  82  83  100 100 80  1   False
3   Grass   Poison  80  100 123 122 120 80  1   False
4   Fire    NaN 39  52  43  60  50  65  1   False
5   Fire    NaN 58  64  58  80  65  80  1   False
6   Fire    Flying  78  84  78  109 85  100 1   False
7   Fire    Dragon  78  130 111 130 85  100 1   False
8   Fire    Flying  78  104 78  159 115 100 1   False

执行df11.groupby("Type 2").mean()时触发错误:TypeError: agg function failed [how->mean,dtype->object]

错误原因

这个错误的核心是df11中的数值列(如HP、Attack等)被识别为object类型,而非int/float这类数值类型。mean()无法对object类型的列执行聚合计算,因此触发报错。另外,布尔类型的Legendary列如果和object类型数值列混合,也会加重这个问题。

你可以先通过df11.dtypes查看各列的数据类型,确认哪些列是object类型。

修复方案

方案1:转换数值列为数值类型

先将需要计算均值的列统一转换为数值类型,再执行聚合:

import pandas as pd

# 指定需要转换的数值列
numeric_columns = ['HP', 'Attack', 'Defense', 'Sp. Atk', 'Sp. Def', 'Speed', 'Generation']
for col in numeric_columns:
    # errors='coerce'会把无法转换的内容转为NaN,不影响后续计算
    df11[col] = pd.to_numeric(df11[col], errors='coerce')

# 可选:将Legendary布尔列转为0/1(True=1,False=0),方便计算均值(代表传奇宝可梦的占比)
df11['Legendary'] = df11['Legendary'].astype(int)

# 现在执行groupby均值计算
result = df11.groupby("Type 2").mean()
print(result)

方案2:仅对数值列执行聚合

如果不想修改原DataFrame的列类型,可以直接筛选出数值列再分组计算:

# 筛选出所有数值类型的列,再分组计算均值
result = df11.groupby("Type 2").select_dtypes(include=['number']).mean()
print(result)

额外提示:处理Type 2中的NaN

如果需要将Type 2为NaN的行单独分组,可以先填充NaN为明确标识(比如"None"):

df11['Type 2'] = df11['Type 2'].fillna('None')
result = df11.groupby("Type 2").select_dtypes(include=['number']).mean()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 15:07:26