如何部分读取巨大的CSV文件? [英] How can I partially read a huge CSV file?

查看:262
本文介绍了如何部分读取巨大的CSV文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的csv文件很大,因此无法将它们全部读入内存.我只想阅读和处理其中的几行内容.因此,我正在Pandas中寻求一个可以处理此任务的函数,基本的python可以很好地处理此任务:

with open('abc.csv') as f:
    line = f.readline()
    # pass until it reaches a particular line number....

但是,如果我在熊猫中这样做,我总是会读第一行:

datainput1 = pd.read_csv('matrix.txt',sep=',', header = None, nrows = 1 )
datainput2 = pd.read_csv('matrix.txt',sep=',', header = None, nrows = 1 )

我正在寻找一些更简单的方法来处理大熊猫中的这项任务.例如,如果我要读取1000到2000之间的行.如何快速执行此操作?

我想使用熊猫,因为我想将数据读入数据框.

解决方案

使用 解决方案

Use chunksize:

for df in pd.read_csv('matrix.txt',sep=',', header = None, chunksize=1):
    #do something

To answer your second part do this:

df = pd.read_csv('matrix.txt',sep=',', header = None, skiprows=1000, chunksize=1000)

This will skip the first 1000 rows and then only read the next 1000 rows giving you rows 1000-2000, unclear if you require the end points to be included or not but you can fiddle the numbers to get what you want.

这篇关于如何部分读取巨大的CSV文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆