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

Pandas分组求均值报错TypeError,计算月度平均降水量遇问题求助

解决Pandas分组计算均值报错:TypeError: agg function failed [how->mean,dtype->object]

报错的核心原因不是month列的类型问题,而是你的precipitation列数据类型为object(通常是字符串或混合了非数值内容),导致无法执行均值计算。以下是具体解决步骤:

  • 第一步:检查precipitation列的类型和内容
    先确认该列的实际情况:

    print(seattle['precipitation'].dtype)
    print(seattle['precipitation'].head(10))
    

    你会看到该列是object类型,可能包含字符串(比如'NA'、'--'这类非数值标记)。

  • 第二步:将precipitation列转换为数值类型
    使用pd.to_numeric强制转换,同时把无法转换的非数值内容转为NaN(后续计算均值时会自动忽略):

    import pandas as pd
    seattle['precipitation'] = pd.to_numeric(seattle['precipitation'], errors='coerce')
    

    如果需要处理NaN,可以根据情况填充(比如用0或列均值):

    # 示例:用0填充空值
    seattle['precipitation'] = seattle['precipitation'].fillna(0)
    
  • 第三步:重新执行分组均值计算
    优化原代码,直接指定计算precipitation列的均值,效率更高:

    monthly_precip = seattle.groupby(['month', 'month_name'])['precipitation'].mean().reset_index()
    

补充提醒:如果数据导入时就出现类型错误,下次导入可以指定dtype参数,比如pd.read_csv('xxx.csv', dtype={'precipitation': float}),避免后续类型转换的麻烦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 08:37:12