Python 如何使用pandas读取大型CSV文件中的几行?

Python 如何使用pandas读取大型CSV文件中的几行?,python,pandas,csv,Python,Pandas,Csv,我有一个CSV文件不适合我的系统内存。使用Pandas,我希望读取散布在文件中的少量行 我认为我可以做到这一点,而无需遵循以下步骤: 在pandas中,我尝试使用skiprows只选择我需要的行 # FILESIZE is the number of lines in the CSV file (~600M) # rows2keep is an np.array with the line numbers that I want to read (~20) rows2skip = (row f

我有一个CSV文件不适合我的系统内存。使用Pandas,我希望读取散布在文件中的少量行

我认为我可以做到这一点,而无需遵循以下步骤:

在pandas中,我尝试使用skiprows只选择我需要的行

# FILESIZE is the number of lines in the CSV file (~600M)
# rows2keep is an np.array with the line numbers that I want to read (~20)

rows2skip = (row for row in range(0,FILESIZE) if row not in rows2keep)
signal = pd.read_csv('train.csv', skiprows=rows2skip)
我希望这段代码能很快返回一个小数据帧。但是,它会在几分钟内开始消耗内存,直到系统变得不负责任。我猜它会先读取整个数据帧,然后再删除rows2skip

为什么这个实现如此低效?如何高效地仅使用rows2keep中指定的行创建数据帧?

试试这个

train = pd.read_csv('file.csv', iterator=True, chunksize=150000)
如果只想读取前n行:

train = pd.read_csv(..., nrows=n)
如果您只想读取从n到n+100的行

train = pd.read_csv(..., skiprows=n, nrows=n+100)

chunksize
应有助于限制内存使用。或者,如果您只需要几行,一种可能的方法是首先读取熊猫之外的所需行,然后仅使用该子集馈送
read\u csv
。代码可以是:

lines = [line for i, line in enumerate(open('train.csv')) if i in lines_to_keep]
signal = pd.read_csv(io.StringIO(''.join(lines)))

您是否尝试过使用
chunksize
读取数据块?也可以在
pandas
中尝试
modlin
。听说读大数据集速度很快!!嘿@RahulAgarwal,莫德林是什么?从来没有听说过。这是一种让你的熊猫阅读速度更快的新方法……只需用谷歌搜索出来谢谢,这实际上是我下一步要尝试的:)但现在我仍然需要以某种方式过滤块中的行。我想知道是否有更直接的方法?我的意思是对块应用相同的rows2skip函数,即train=pd.read\u csv('file.csv',iterator=True,chunksize=150000,skiprows=rows2skip),我希望这能起作用(chunksize和skiprows的混合),但它不会——它同样阻塞内存。如果我们指定要跳过的行,pandas似乎仍然试图立即加载所有内容。谢谢。这是一个好主意,但是阅读要花很长时间。