Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read data in chunks in Python dataframe?

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

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

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

Please advise the fix.

like image 334
Geet Avatar asked Sep 08 '16 07:09

Geet


1 Answers

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

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

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

See pandas docs.

like image 51
jezrael Avatar answered Oct 24 '22 14:10

jezrael