Working with large CSV files in Python

large csv files in pythonI’m currently working on a project that has multiple very large CSV files (6 gigabytes+). Normally when working with CSV data, I read the data in using pandas and then start munging and analyzing the data. With files this large, reading the data into pandas directly can be difficult (or impossible) due to memory constrictions, especially if you’re working on a prosumer computer. In this post, I describe a method that will help you when working with large CSV files in python.

While it would be pretty straightforward to load the data from these CSV files into a database, there might be times when you don’t have access to a database server and/or you don’t want to go through the hassle of setting up a server.  If you are going to be working on a data set long-term, you absolutely should load that data into a database of some type (mySQL, postgreSQL, etc) but if you just need to do some quick checks / tests / analysis of the data, below is one way to get a look at the data in these large files with python, pandas and sqllite.

To get started, you’ll need to import pandas and sqlalchemy. The commands below will do that.

Next, set up a variable that points to your csv file.  This isn’t necessary but it does help in re-usability.

With these three lines of code, we are ready to start analyzing our data. Let’s take a look at the ‘head’ of the csv file to see what the contents might look like.

This command uses pandas’ “read_csv” command to read in only 5 rows (nrows=5) and then print those rows to the screen. This lets you understand the structure of the csv file and make sure the data is formatted in a way that makes sense for your work.

Before we can actually work with the data, we need to do something with it so we can begin to filter it to work with subsets of the data. This is usually what I would use pandas’ dataframe for but with large data files, we need to store the data somewhere else. In this case, we’ll set up a local sqllite database, read the csv file in chunks and then write those chunks to sqllite.

To do this, we’ll first need to create the sqllite database using the following command.

Next, we need to iterate through the CSV file in chunks and store the data into sqllite.

With this code, we are setting the chunksize at 100,000 to keep the size of the chunks managable, initializing a couple of iterators (i=0, j=0) and then running through a for loop.  The for loop reads a chunk of data from the CSV file, removes spaces from any of column names, then stores the chunk into the sqllite database (df.to_sql(…)).

This might take a while if your CSV file is sufficiently large, but the time spent waiting is worth it because you can now use pandas ‘sql’ tools to pull data from the database without worrying about memory constraints.

To access the data now, you can run commands like the following:

Of course, using ‘select *…’ will load all data into memory, which is the problem we are trying to get away from so you should throw from filters into your select statements to filter the data. For example:

 

Author: Eric Brown

Eric D. Brown , D.Sc. has a doctorate in Information Systems with a specialization in Data Sciences, Decision Support and Knowledge Management. He writes about utilizing python for data analytics at pythondata.com and the crossroads of technology and strategy at ericbrown.com

19
Leave a Reply

avatar
8 Comment threads
11 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
13 Comment authors
Eric BrownPavithrahan phamJullyConnor Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Pouya Sobhanipour
Guest
Pouya Sobhanipour

Hi recently i”v been trying to use some classification function over a large csv file (consisting of 58000 instances (rows) & 54 columns ) for this approach i need to mage a matrix out of the first 54 columns and all the instances which gives me an array . but the problem is memory can not handle this large array so i searched and found your website now , at the end you used df = pd.read_sql_query(‘SELECT * FROM table’, csv_database) first : the the shows syntax error second : i need to have all the columns from 1 to… Read more »

David
Guest
David

Alternatively, you can do the filtering natively in Pandas: # columns we wish to keep/filter on cols_to_keep = [‘id’, ‘member_id’, ‘loan_amnt’, ‘funded_amnt’] # setup dataframe iterator, the ‘usecols’ parameter filters the columns in the csv df_iter = pd.read_csv(r’/tmp/z_data/LoanStats_2016Q1.csv.zip’, skiprows=1, compression=’zip’, chunksize=20000, usecols=cols_to_keep) dfs = [] # this list will store the filtered dataframes for concatenation for df in df_iter: temp_df = (df.rename(columns={col: col.lower() for col in df.columns}) # filter .pipe(lambda x: x[x.funded_amnt > 10000])) dfs += [temp_df.copy()] # combine filtered dfs into large output df concat_df = pd.concat(dfs)

Robert
Guest
Robert

Thanks Eric, very helpful. How do you clear your cache after the SELECT operation?

Berry
Guest
Berry

I did everything the way you said, but i can’t query the database. Can you help me how to do it? I know i have some missing knowledge. I get the error: OperationalError: (sqlite3.OperationalError) near “table”: syntax error [SQL: ‘SELECT * FROM table’]
I think i didn’t created a table inside the database or i dont know, but i imported from my csv file the way you did.

Travis
Guest
Travis

I copied this example exactly and had the same error. Put table in double quotes and it worked.
df = pd.read_sql_query(‘SELECT * FROM “table”‘, csv_database)

Connor
Guest
Connor

THANK YOU! I was stuck on this as well, adding double quotes around “table” solved for me too.

Jully
Guest
Jully

Thank you.
I had the same error and your solution worked.

rouie
Guest
rouie

Thanks.
This provided to be very useful.

UserName
Guest

I get an error on this line: df.index += j
TypeError: can only concatenate tuple (not “int”) to tuple

han pham
Guest
han pham

Thanks a lot! Really helpful.

Pavithra
Guest
Pavithra

Hi ,
I am having a csv with nearly 100 rows and 100k columns. I would like to know how to chunk the dataset. In most case, i noticed only data chunks by rows but how do we handle for columns