如何将Pandas DataFrame中'User_total_Review'列转为int类型?
解决Pandas DataFrame列转int时的ValueError问题
你的报错是因为User_total_Review列中存在带逗号的字符串(比如'1,'),直接用astype(int)转换时,Python的int()函数无法解析这种格式的字符串。解决步骤如下:
方法一:先清理逗号再转换
先通过字符串替换去掉所有逗号,再转换为int类型:
# 移除列中所有字符串里的逗号 filtered_df['User_total_Review'] = filtered_df['User_total_Review'].str.replace(',', '') # 转换为int类型 filtered_df['User_total_Review'] = filtered_df['User_total_Review'].astype(int)
方法二:用pd.to_numeric处理异常(更稳健)
如果列中可能存在其他无法转换的异常值,可以用pd.to_numeric配合errors='coerce'将无效值转为NaN,再用Nullable integer类型(Int64)存储:
# 清理逗号后转换,异常值转为NaN filtered_df['User_total_Review'] = pd.to_numeric( filtered_df['User_total_Review'].str.replace(',', ''), errors='coerce' ).astype('Int64')
注意
- 如果使用普通
int类型,列中不能有NaN值;如果需要保留NaN,必须用Int64(大写I)这种Nullable整数类型。 - 若列中还有其他非数字字符(比如空格、字母),需要先对应清理后再转换。
内容的提问来源于stack exchange,提问作者Neha Shaw
相关产品推荐
相关产品推荐

