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

将object类型转为int后仍报类型错误,无法对runs列执行操作

解决方法
  • 首先要注意:astype(int)不会直接修改原DataFrame的列,必须把转换结果重新赋值回原列,否则原列还是字符串类型:
    bow_df['runs'] = bow_df['runs'].astype(int)
    
  • 如果上面的代码报错,说明runs列里存在无法转成整数的脏数据(比如空字符串、字母、带符号的异常值),用pd.to_numeric配合errors='coerce'能把无效值转成NaN,再处理更稳妥:
    import pandas as pd
    bow_df['runs'] = pd.to_numeric(bow_df['runs'], errors='coerce')
    # 要是需要把NaN替换成具体数值(比如0),再转成整数
    bow_df['runs'] = bow_df['runs'].fillna(0).astype(int)
    
  • 先验证转换是否成功,避免白忙活:
    print(bow_df['runs'].dtype)  # 正常会输出int64/int32
    
  • 搞定类型转换后,就能顺利执行比较和聚合操作了:
    # 筛选runs大于25的行
    filtered_data = bow_df[bow_df['runs'] > 25]
    # 常用聚合操作示例
    print(bow_df['runs'].mean())  # 平均值
    print(bow_df['runs'].sum())   # 总和
    print(bow_df['runs'].median())# 中位数
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 22:42:06