Pandas读取大文件遇Cert#列类型错误:定位错误行与替换异常值
Pandas读取大文件时处理
Cert#列类型错误的解决方案 问题背景
读取大型制表符分隔文件时,预先声明Cert#列为np.int64类型,但触发类型转换错误,因文件体积过大无法定位异常行和值;已尝试on_bad_lines='warn'参数,但未达到预期效果。
原代码
import pandas as pd import numpy as np my_cols = ["Date", "code", "many other cols", "Cert#", "Column 19"] my_types = {"code": str, "result#": np.float64, "Cert#": np.int64} df = pd.read_table( file_path, usecols=my_cols, parse_dates=["Date"], dtype=my_types, sep='\t', engine='python', encoding="ISO-8859-1", on_bad_lines='warn' )
报错信息
ValueError: Unable to convert column Cert# to type int64
问题解答
1. 打印错误行查看异常Cert#值
on_bad_lines='warn'仅处理列数不匹配的坏行,对类型转换失败的情况无效。可以通过以下步骤定位异常行:
- 先跳过
Cert#的类型声明,读取全部数据 - 筛选出无法转换为整数的
Cert#行
# 读取数据时暂不指定Cert#的类型 df = pd.read_table( file_path, usecols=my_cols, parse_dates=["Date"], dtype={k:v for k,v in my_types.items() if k != "Cert#"}, sep='\t', engine='python', encoding="ISO-8859-1" ) # 筛选出Cert#列无法转换为整数的行 invalid_rows = df[pd.to_numeric(df["Cert#"], errors='coerce').isna()] print(invalid_rows)
2. 将错误值替换为-999
有两种实现方式:
方式一:读取时直接处理
使用converters参数自定义Cert#列的转换逻辑,遇到无法转换的情况返回-999:
def convert_cert(x): try: return int(x) except (ValueError, TypeError): return -999 df = pd.read_table( file_path, usecols=my_cols, parse_dates=["Date"], dtype={k:v for k,v in my_types.items() if k != "Cert#"}, sep='\t', engine='python', encoding="ISO-8859-1", converters={"Cert#": convert_cert} )
方式二:读取后批量处理
如果已完成数据读取(未指定Cert#类型),可通过pd.to_numeric配合fillna批量替换:
df["Cert#"] = pd.to_numeric(df["Cert#"], errors='coerce').fillna(-999).astype(np.int64)
内容的提问来源于stack exchange,提问作者Shane S
相关产品推荐
相关产品推荐

