将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
相关产品推荐
相关产品推荐

