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

Pandas分组求均值报错No numeric types to aggregate 解决方法咨询

解决pandas分组求均值报错No numeric types to aggregate的问题

你遇到的这个报错核心原因非常明确——days_outstanding列的数据类型不是数值型(大概率是object/字符串类型),pandas无法对非数值类型的列执行均值这类聚合计算。而之前的count()能成功,是因为它只统计非缺失值的数量,不管列类型是数值还是字符串,只要不是空值都会被计数。

下面是一步步的解决流程:

1. 先确认列的真实数据类型与内容

把你没写完的检查语句补全,执行这两行代码,明确问题所在:

print(df['days_outstanding'].dtype)  # 查看列的数据类型
print(df['days_outstanding'].head(10))  # 查看前10条数据的具体内容

这会帮你排查:是纯字符串格式的数字?还是带单位的字符串(比如"3天")?或是存在特殊字符/空值?

2. 将列转换为数值类型

根据检查结果选择对应的处理方式:

  • 如果是纯字符串格式的数字:直接用pd.to_numeric转换,同时处理无法转换的异常值:
    import pandas as pd
    df['days_outstanding'] = pd.to_numeric(df['days_outstanding'], errors='coerce')
    # errors='coerce'会把无法转换的内容转为NaN,之后可以按需处理空值
    df = df.dropna(subset=['days_outstanding'])  # 删除含NaN的行
    # 或者用均值填充空值:df['days_outstanding'] = df['days_outstanding'].fillna(df['days_outstanding'].mean())
    
  • 如果字符串带单位(比如"5天"):先提取数字部分再转换:
    df['days_outstanding'] = df['days_outstanding'].str.extract('(\d+)').astype(int)
    

3. 重新执行均值计算

完成类型转换后,再运行你原来的分组均值代码就可以正常执行了:

df_days = df.groupby(['code', 'year_month'])['days_outstanding'].mean().reset_index(name='avg_days_outstanding')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:19:21