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

使用pandas.read_csv批量跳行读取大CSV文件遇问题求助

分块读取CSV时跳过指定行失效的问题排查与解决

我需要分块读取大型CSV文件,规则是先读前10行(0-9),跳过10-19行,再读20-29行,跳过30-39行,以此循环。但我写的代码只跳过了10-19行,后面的行都没跳过,完全不符合预期:

#initializing n1 and n2 variable
n1=1
n2=2
#reading data in chunks
for chunk in pd.read_csv('../input/train.csv',chunksize=10, dtype=dtypes,skiprows=list(range( ((n1*10)+1), ((n2*10) +1) ))):
    sample_chunk=chunk
    #displaying the sample_chunk
    print(sample_chunk)
    #incrementing n1
    n1=n1+2
    #incrementing n2
    n2=n2+2

问题根源

你这段代码的核心bug是:pd.read_csv()的skiprows参数在函数调用的那一刻就固定了,循环里修改n1和n2根本不会改变它!

也就是说,第一次执行pd.read_csv()时,skiprows被计算为range(11,21)(对应CSV里的10-19行,注意pandas的行号是从0开始计数的),之后不管你怎么循环修改n1、n2,这个参数都不会重新计算。所以后面的分块读取都是按顺序读剩下的所有行,完全没再跳过任何内容。

正确的实现方式

方法一:动态跳过块(适合超大型CSV,内存友好)

这个方法不需要提前计算所有行号,直接按“读一块、跳一块”的逻辑处理,效率最高:

import pandas as pd

chunksize = 10
# 创建CSV读取迭代器
reader = pd.read_csv('../input/train.csv', chunksize=chunksize, dtype=dtypes)

while True:
    try:
        # 读取我们需要的10行块
        target_chunk = next(reader)
        print(target_chunk)
        # 跳过下一个10行块
        next(reader)
    except StopIteration:
        # 迭代器耗尽,退出循环
        break

如果你的CSV有表头,不用担心——pd.read_csv()会自动把第一行作为列名,第一个next(reader)返回的是表头之后的10行数据,完全符合你的读取规则。

方法二:提前计算所有要读取的行号(适合行数较少的场景)

如果CSV总行数不算特别大,可以先算出所有需要读取的行号,再分块读取:

import pandas as pd

# 先获取CSV总行数(只扫行不读内容,内存开销小)
total_rows = sum(1 for _ in open('../input/train.csv'))
header_exists = True  # 根据你的CSV实际情况修改

# 计算所有要读取的行号
read_rows = []
if header_exists:
    read_rows.append(0)  # 保留表头行

# 循环生成数据行的读取范围:0-9,20-29,40-49...(这里的行号包含表头的话是从0开始)
start_row = 1 if header_exists else 0
for i in range(start_row, total_rows, 20):
    read_rows.extend(range(i, i + 10))

# 分块读取指定行
chunksize = 10
for idx in range(0, len(read_rows), chunksize):
    current_rows = read_rows[idx:idx+chunksize]
    # 用lambda判断哪些行要跳过
    chunk = pd.read_csv('../input/train.csv', skiprows=lambda x: x not in current_rows, dtype=dtypes)
    print(chunk)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 03:50:42