pandas 如何在 Python 数据帧中分块读取数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39384539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:58:15  来源:igfitidea点击:

How to read data in chunks in Python dataframe?

pythoncsvpandasdataframechunks

提问by Geet

I want to read the file f in chunks to a dataframe. Here is part of a code that I used.

我想将文件 f 分块读取到数据帧中。这是我使用的代码的一部分。

for i in range(0, maxline, chunksize):
df = pandas.read_csv(f,sep=',', nrows=chunksize, skiprows=i)
df.to_sql(member, engine, if_exists='append',index= False, index_label=None, chunksize=chunksize)

I get the error:

我收到错误:

pandas.io.common.EmptyDataError: No columns to parse from file

pandas.io.common.EmptyDataError:没有要从文件解析的列

The code works only when the chunksize >= maxline (which is total lines in file f). However, in my case, the chunksize<=maxline.

该代码仅在 chunksize >= maxline(即文件 f 中的总行数)时有效。但是,就我而言,chunksize<=maxline。

Please advise the fix.

请建议修复。

回答by jezrael

I think it is better to use the parameter chunksizein read_csv. Also, use concatwith the parameter ignore_index, because of the need to avoid duplicates in index:

我认为这是更好地使用该参数chunksizeread_csv。此外,使用concat参数ignore_index,因为需要避免重复index

chunksize = 5
TextFileReader = pd.read_csv(f, chunksize=chunksize)

df = pd.concat(TextFileReader, ignore_index=True)

See pandas docs.

请参阅Pandas文档