问题:Python Pandas:如何仅读取CSV文件的前n行?

我有一个非常大的数据集,我无法读取其中的整个数据集。因此,我正在考虑只读取其中的一个数据块进行训练,但是我不知道该怎么做。任何想法将不胜感激。

I have a very large data set and I can’t afford to read the entire data set in. So, I’m thinking of reading only one chunk of it to train but I have no idea how to do it. Any thought will be appreciated.


回答 0

如果您只想读取前999,999行(非标题):

read_csv(..., nrows=999999)

如果您只想读取1,000,000 … 1,999,999行

read_csv(..., skiprows=1000000, nrows=999999)

nrows:int,默认值无要读取的文件行数。对读取大文件有用*

skiprows:类似于列表或整数的行号,在文件开头要跳过(索引为0)或要跳过的行数(整数)

对于大文件,您可能还需要使用chunksize:

chunksize:int,默认为None返回TextFileReader对象进行迭代

pandas.io.parsers.read_csv文档

If you only want to read the first 999,999 (non-header) rows:

read_csv(..., nrows=999999)

If you only want to read rows 1,000,000 … 1,999,999

read_csv(..., skiprows=1000000, nrows=999999)

nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*

skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file

and for large files, you’ll probably also want to use chunksize:

chunksize : int, default None Return TextFileReader object for iteration

pandas.io.parsers.read_csv documentation


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。