Python para Data Science e Analytics
Python para Data Science e Analytics › Guides › How to read a very large CSV in pandas without freezing your

How to read a very large CSV in pandas without freezing your computer

The safe way to read a very large CSV in pandas is to stop loading the whole file at once: pass chunksize to pd.read_csv so the file is processed in parts, and combine it with usecols and dtype so only the columns and types you need are brought in. Peak memory then stays close to one chunk plus whatever result you chose to keep, instead of the full file size. The steps below show the code, the checks, and when each option is the right one.

Topics: csv grande, chunks, pandas

Why does pandas freeze or crash when opening a big CSV?

pd.read_csv returns a complete DataFrame. It reads the file, infers a dtype for every column, and builds the entire structure in RAM before handing anything back to you. A file that is small on disk can produce a much larger DataFrame, because text is stored as object with pointers and strings, and numbers are read as int64 or float64 even when a narrower type would do.

When the total does not fit in RAM, the operating system starts swapping or kills the process. The usual symptoms are MemoryError, the process being terminated with no clear message, and the machine slowing down while the file is open.

So the useful question is not only how big the file is on disk. It is how big the resulting DataFrame will be, and what the smallest slice you actually need is.

How do you read a big CSV in chunks with pd.read_csv?

chunksize is counted in rows, not bytes. Instead of one DataFrame, read_csv returns a TextFileReader you can iterate over: each iteration yields a DataFrame with up to that many rows, and the previous chunk can be released.

Because the count is in rows, the real size of each chunk depends on how many columns the file has and what types they carry. Measure with a small chunk before fixing the number.

In recent pandas versions the returned object also works as a context manager, which closes the file when the block ends.

How do usecols and dtype cut memory before the data is loaded?

Reading only what you will use usually saves more than tuning chunksize alone. usecols keeps columns you never touch out of the DataFrame, and dtype stops pandas from guessing and then storing everything in 64 bits.

Columns with few distinct values, such as a state code or a category label, can be declared as category. Dates can be parsed during the read with parse_dates. For integers and floats, pick the precision the data actually requires.

low_memory controls how pandas splits the file internally while inferring types; it does not make the final DataFrame smaller. If you see a mixed-dtype warning on a column, declaring that column's dtype is what removes it.

How do you process in chunks and keep only the result?

In most cases you do not need the whole file in memory, only a result: a sum per state, a count per day, an average per product. Those can be computed chunk by chunk, accumulating just the partial from each piece.

If the partial for each chunk is still large, shrink it before storing: group inside the chunk, then concatenate the partials. If the total still does not fit, write each partial to CSV or Parquet inside the loop and consolidate in a second pass. The goal is that peak memory stays bounded by the current chunk plus the accumulator.

Which read_csv option should you reach for first?

The options solve different problems, and mixing them up is the usual reason a read still runs out of memory. The table maps each one to what it actually changes.

The order that tends to work: check the real size of the DataFrame first, drop columns with usecols, narrow types with dtype, and only then split the read with chunksize.

Where can you learn pandas from zero, with a real project?

Reading in chunks, narrowing dtypes and profiling a DataFrame are pandas skills, and they are easier to absorb when the course walks through them in order rather than assuming them. The Python for Data Science and Analytics course goes from zero to advanced across three main modules, Basic, Intermediate and Advanced, plus bonus modules, and it covers IDE and Jupyter Notebook setup, basic functions, NumPy and Pandas, user-defined functions, loops and conditionals, data visualization, data cleaning and preparation, and outlier detection.

The machine learning part covers linear and logistic regression, K-Means, SVM, Naive Bayes, decision tree, Random Forest, Gradient Boosting, XGBoost, LightGBM, feature selection and cross-validation. It closes with a final project: end-to-end exploratory analysis and machine learning.

Lessons are recorded in high quality and watched at your own pace, with guided exercises and real market projects for your portfolio. Access is unlimited with no expiry, there is a completion certificate, and an exclusive community for networking. You do not need to know how to program before starting. The price is R$ 470, or 12 installments of R$ 20.37 on the card, paid through the Hotmart checkout with card or boleto. Details are on python.paanalytics.net, and enrollment starts at the Hotmart checkout link.

Learn pandas from scratch, ending in a full machine learning project

Secure payment via Hotmart, up to 12 installments.

Enroll now Product site

Frequently asked questions

What chunksize should I start with?

There is no universal number, because chunksize is counted in rows and the memory per row depends on your columns and dtypes. Start with a value you can measure, run one chunk, and check its size with chunk.memory_usage(deep=True).sum(). Raise or lower the number until a chunk sits comfortably in the RAM you can spare.

Does low_memory=False reduce memory usage?

No. low_memory changes how pandas divides the file internally while inferring types, not the size of the final DataFrame. Setting it to False can reduce mixed-dtype warnings but does not make the result smaller. Declaring dtype explicitly is what actually lowers the footprint.

How do I check how much memory a DataFrame is using?

Compare df.info(memory_usage='deep') for text columns, because the default report underestimates object columns, and df.memory_usage(deep=True).sum() for a single number. Run the same check on one chunk and multiply by the number of chunks to estimate whether the full read would fit.

What if a single chunk still does not fit in memory?

Then lower chunksize, cut columns further with usecols, or narrow dtypes to smaller ints and floats. If one row-level slice is still too heavy, the computation itself needs to change: aggregate inside each chunk and keep only the grouped partials, writing them to CSV or Parquet and consolidating in a second pass.

Is it faster to convert the CSV to Parquet first?

It can help when you will read the same data many times, since Parquet stores types and reads column by column. For a one-off pass, reading the CSV in chunks avoids the conversion step entirely. If you do convert, do it chunk by chunk and write each part separately rather than building the full DataFrame first.

Ler em português →