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

Pandas读取800万行CSV报ParserError: EOF inside string错误

问题场景

在配备8GB内存、安装Anaconda 4的个人电脑上,使用Pandas读取维度为800万行×20列的CSV文件ec_all.csv时触发ParserError报错,读取代码及完整报错栈如下:

filename= "ec_all.csv"
df= pd.read_csv (filename,encoding= 'unicode_escape', low_memory=False, parse_dates=["FIRSTCLASS"])

---------------------------------------------------------------------------
ParserError                               Traceback (most recent call last)
<ipython-input-5-62582a9f3753> in <module>()
      1 # Reading data from file to create data frame
----> 2 df= pd.read_csv (filename,encoding= 'unicode_escape', low_memory=False, parse_dates=["FIRSTCLASS"])

C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision)
    653                     skip_blank_lines=skip_blank_lines)
    654 
--> 655         return _read(filepath_or_buffer, kwds)
    656 
    657     parser_f.__name__ = name

C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\parsers.py in _read(filepath_or_buffer, kwds)
    409 
    410     try:
--> 411         data = parser.read(nrows)
    412     finally:
    413         parser.close()

C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\parsers.py in read(self, nrows)
    980                 raise ValueError('skipfooter not supported for iteration')
    981 
--> 982         ret = self._engine.read(nrows)
    983 
    984         if self.options.get('as_recarray'):

C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\parsers.py in read(self, nrows)
   1717     def read(self, nrows=None):
   1718         try:
-> 1719             data = self._reader.read(nrows)
   1720         except StopIteration:
   1721             if self._first_chunk:

pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader.read (pandas\_libs\parsers.c:10885)()

pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader._read_rows (pandas\_libs\parsers.c:12054)()

pandas\_libs\parsers.pyx in pandas._libs.parsers.raise_parser_error (pandas\_libs\parsers.c:28765)()

ParserError: Error tokenizing data. C error: EOF inside string starting at line 2119608

核心报错信息:Error tokenizing data. C error: EOF inside string starting at line 2119608

补充验证信息

同一段读取代码在以下两种场景可正常运行无报错:

  • 同一台8GB内存PC上,仅读取该文件前10000条样本数据
  • 配备16GB内存、安装Anaconda 3的另一台PC上,读取该文件全量数据
问题原因

该报错属于内存不足触发的解析假报错,并非CSV文件本身存在格式损坏:

  • 若文件第2119608行真的存在未闭合字符串的格式问题,16G内存设备全量读取、同设备读取到报错行位置时都会触发相同报错,与验证结果矛盾
  • 代码中设置了low_memory=False,Pandas会一次性加载全量数据推断所有字段类型,8G内存设备解析800万行×20列数据时,解析到报错行附近内存耗尽,读取进程被强制截断,C引擎误判为“字符串未闭合就到达文件尾”,抛出对应错误。
解决方案

按优先级从高到低可选择以下方案:

  • 主动指定字段类型降低内存占用。不要依赖Pandas自动推断字段类型,通过dtype参数给每个字段指定匹配的最小存储类型:枚举值少的文本字段设为category类型,整数类字段按需用int8/int16/int32代替默认int64,浮点类字段按需用float32代替默认float64,整体内存占用可降低50%~70%,适配8G内存设备读取需求。示例代码:
import pandas as pd
filename = "ec_all.csv"
# 按实际表字段调整类型映射
dtype_config = {
    "分类字段名": "category",
    "整数字段名": "int32",
    "浮点字段名": "float32"
}
df = pd.read_csv(
    filename,
    encoding='unicode_escape',
    low_memory=False,
    parse_dates=["FIRSTCLASS"],
    dtype=dtype_config
)
  • 分块读取后拼接。如果指定类型后内存仍不足,通过chunksize参数按固定行数分批读取数据,每批加载后存入列表,最后统一拼接为完整DataFrame,避免一次性占满内存。示例代码:
import pandas as pd
filename = "ec_all.csv"
chunk_container = []
# 每次读取50万~100万行,可根据剩余内存调整数值
for chunk in pd.read_csv(
    filename,
    encoding='unicode_escape',
    parse_dates=["FIRSTCLASS"],
    chunksize=1000000
):
    chunk_container.append(chunk)
df = pd.concat(chunk_container, ignore_index=True)
  • 更换Python解析引擎。将Pandas默认的C解析引擎更换为Python引擎,对大文件内存溢出的容错性更强,只需新增参数engine='python'即可,缺点是读取速度比C引擎慢30%左右。

❌ 避坑:不要直接添加error_bad_lines=False参数跳过报错,该参数会直接丢弃解析器判定为出错的行,在内存不足引发的假报错场景下会丢失大量有效数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.31 12:03:23