数据转换报错排查:ValueError: invalid literal for int() with base 10: '1500'
解决方案:处理含不可见字符的价格列转换问题
问题原因
你遇到的ValueError是因为now_prices列的字符串中存在肉眼不可见的Unicode控制字符(比如零宽连接符、零宽空格这类),这些字符不属于数字范畴,直接用int()转换就会报错。之前的操作可能只清理了可见非数字字符,残留的隐藏脏数据即使表面转成了int,导出Excel时仍会触发错误。
解决步骤
先彻底清洗now_prices列的隐藏脏字符,再转换类型,最后用previous_prices填充空值:
方法1:正则提取纯数字
直接提取字符串中的连续数字,忽略所有非数字字符(包括隐藏的):
import pandas as pd # 清洗now_prices:提取所有连续数字,空值/无数字内容转为NaN df['now_prices_cleaned'] = df['now_prices'].astype(str).str.extract(r'(\d+)') # 转换为数值类型,错误值强制转为NaN df['now_prices_cleaned'] = pd.to_numeric(df['now_prices_cleaned'], errors='coerce') # 用previous_prices填充空值,最终转为int类型 df['now_prices_final'] = df['now_prices_cleaned'].fillna(df['previous_prices']).astype(int) # 导出Excel df.to_excel('cleaned_prices.xlsx', index=False)
方法2:清除Unicode控制字符后提取数字
如果正则提取不够彻底,可先清除所有Unicode控制字符,再提取数字:
import pandas as pd import re import unicodedata def clean_price_str(s): if pd.isna(s): return s # 过滤所有Unicode控制字符(隐藏字符) cleaned = ''.join(c for c in str(s) if not unicodedata.category(c).startswith('C')) # 提取数字部分 match = re.search(r'\d+', cleaned) return match.group() if match else None # 清洗列 df['now_prices_cleaned'] = df['now_prices'].apply(clean_price_str) # 后续转换和填充同方法1 df['now_prices_cleaned'] = pd.to_numeric(df['now_prices_cleaned'], errors='coerce') df['now_prices_final'] = df['now_prices_cleaned'].fillna(df['previous_prices']).astype(int) df.to_excel('cleaned_prices.xlsx', index=False)
关键说明
- 不要先填充空值再转换类型:应先清洗并转换
now_prices,确保所有可转换内容变为数值后,再用previous_prices填充空值,避免脏数据被带入最终列。 - 导出前检查数据类型:用
df['now_prices_final'].dtype确认类型为int64,确保无残留的object类型数据。
内容的提问来源于stack exchange,提问作者Elkhan
相关产品推荐
相关产品推荐

