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:

 

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

6 thoughts on “Working with large CSV files in Python

  1. 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 53 out of 54 columns
    what should i do ?

    1. The code df = pd.read_sql_query(‘SELECT * FROM table’, csv_database) is just a sample of what you could do with the data once it is loaded into the database. For what you are trying to do, you’ll need to customize that code for your database, table and data.

      1. thanks for your reply
        but would you let me know how to do this ?
        how to customize that code for my data base ?

        1. Unfortunately, there’s too many unknowns for me to help. I have no idea what your database looks like, what it is called or how you have it set up.

          Good luck.

  2. 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)

Leave a Reply

Your email address will not be published. Required fields are marked *