Why is Pandas consuming so much memory while processing large CSV files?

Tom Zerega
Updated 26 mins ago in

I’ve been working with multiple CSV files that need to be combined, cleaned and transformed before further analysis. The combined dataset is around 3 GB, but the memory consumption becomes significantly higher when performing merge and groupby operations in Pandas.

I’ve tried specifying data types, removing unnecessary columns and processing files in chunks. While these changes have helped, some operations still cause the application to run out of memory.

Would switching to Polars or DuckDB be a better long-term solution, or are there additional ways to optimise Pandas for this kind of workload?

I’d appreciate hearing from anyone who has faced similar challenges while working with large datasets.

  • 1
  • 6
  • 26 minutes ago
 
14 mins ago

I’d first check when memory spikes. Does it happen during read_csv(), or does the file load successfully and then run out of memory during a merge or sort? Those are different problems.

If it happens during the read, load a sample and run df.memory_usage(deep=True).sort_values(ascending=False). That shows which columns are taking up the most space. CSV stores text on disk. Once parsed, the DataFrame has its own memory footprint, and long text columns can take up much of it. I’d start with usecols to read only the columns the analysis needs, then specify types where the schema is known. Keep identifiers like policy numbers as strings if leading zeros matter. 

If the spike happens during a merge, check whether the join keys repeat on both sides. For example, three rows with the same key on the left and four on the right produce twelve matching rows for that key. If you expect one lookup row per key, validate="many_to_one" makes pandas flag a violation instead of silently expanding the result.

For a task like counting records or summing amounts by category, chunksize is a good fit. Summarize each chunk and combine the summaries. If you collect all the chunks and concatenate them at the end, you still have to fit the full result in memory. 

Which line triggers the spike in your case? The read_csv() call and the next operation would be the two most useful things to share.

 
 
  • Liked by
Reply
Cancel
Loading more replies