About Skills Projects Blog Contact View my CV ↗ Español
Large data analysis with Python: from pandas to Polars and DuckDB

Large data analysis with Python: from pandas to Polars and DuckDB

How to analyze datasets that don't fit in memory with Python: Polars, DuckDB, chunking, and strategies that avoid OOM.

By Omar Flores
Table of Contents

Imagine trying to analyze an entire national census using a pocket calculator. The calculator works, but each operation takes minutes and memory fills up before finishing the first column. The problem is not the calculator: it was designed for a different scale.

Pandas is that calculator. It is excellent for datasets that fit in memory (hundreds of thousands of rows), but when the dataset has tens of millions of rows or gigabytes of data, pandas drowns: it consumes all RAM, becomes slow, and eventually fails with a MemoryError. The problem is not pandas. The problem is using pandas for data that does not fit in memory.


The problem: data that does not fit in RAM

A pandas DataFrame loads everything into memory. A 5 GB CSV becomes a 10-15 GB DataFrame in RAM (because pandas uses inefficient data types: strings as objects, int64 for everything). If your machine has 16 GB of RAM, the system starts using swap, and the analysis that took 10 seconds now takes 10 minutes.

Signs that you are in this problem:

  • The script takes minutes to load the file.
  • Memory usage rises to 90%+ and the system freezes.
  • MemoryError appears or the process is killed by the OOM killer.
  • Adding a new column doubles memory consumption.

The tools: each for its scale

pandas: the standard (for data that fits in memory)

pandas is the default tool. Huge ecosystem, excellent documentation, everyone knows it. Works well up to ~1-2 GB of data in RAM. Beyond that, it starts to suffer.

Polars: the successor (fast and efficient)

Polars is a DataFrame library written in Rust. It is faster than pandas (10-100x on common operations) and uses less memory (optimized data types, lazy execution). The API is similar to pandas but with important differences.

import polars as pl

df = pl.read_csv("data.csv")  # loads into memory
result = (
    df.filter(pl.col("amount") > 100)
    .group_by("category")
    .agg(pl.col("amount").sum())
    .sort("amount", descending=True)
)

Polars has two modes: eager (executes immediately, like pandas) and lazy (builds an execution plan and optimizes before running). Lazy mode is where Polars shines: it optimizes the plan, removes unnecessary columns, and reduces memory consumption.

lf = pl.scan_csv("data.csv")  # lazy: does not load data
result = (
    lf.filter(pl.col("amount") > 100)
    .group_by("category")
    .agg(pl.col("amount").sum())
    .collect()  # here it executes the optimized plan
)

DuckDB: SQL over files (without loading into memory)

DuckDB is an embedded analytical database that runs SQL directly on CSV, Parquet, or JSON files without loading them into memory. Ideal when you already know SQL and want to analyze large data without changing paradigms.

import duckdb

result = duckdb.sql("""
    SELECT category, SUM(amount) as total
    FROM 'data.csv'
    WHERE amount > 100
    GROUP BY category
    ORDER BY total DESC
""").df()  # returns a pandas DataFrame

DuckDB does not need to load the whole file: it reads only the necessary columns and applies filters in streaming. A 10 GB CSV is analyzed in seconds with a few MB of RAM.

Dask: distributed pandas (for clusters)

Dask scales pandas to multiple machines. It splits the DataFrame into partitions and processes each in parallel. The option when data does not fit on a single machine.

PyArrow: the format (not the tool)

PyArrow is the library that defines the Apache Arrow format in Python. It is not an analysis tool, but it is the base of Polars, DuckDB, and pandas 2.0. Its columnar format is more efficient than pandas (strings as byte arrays, not objects).


Strategies for large data

1. Use Parquet instead of CSV

CSV is plain text: slow to parse, no data types, no compression. Parquet is columnar, compressed, and typed. A Parquet file is 5-10x smaller than the equivalent CSV and reads 10-50x faster.

# Convert once
df = pl.read_csv("data.csv")
df.write_parquet("data.parquet")

# Read later (much faster)
df = pl.read_parquet("data.parquet")

2. Chunking (process in parts)

If you cannot load everything, process in chunks and aggregate results.

import pandas as pd

totals = {}
for chunk in pd.read_csv("data.csv", chunksize=100_000):
    for category, amount in chunk.groupby("category")["amount"].sum().items():
        totals[category] = totals.get(category, 0) + amount

Limitation: works for aggregations, but not for operations requiring all data (sorting, full join).

3. Lazy evaluation

Instead of executing each operation immediately, build a plan and execute once at the end. Polars and DuckDB do this automatically.

4. Filter before loading

Do not load everything to filter later. Filter on read.

# pandas: load all, then filter (bad)
df = pd.read_csv("data.csv")
df = df[df["amount"] > 100]

# Polars: filter during read (good)
df = pl.scan_csv("data.csv").filter(pl.col("amount") > 100).collect()

# DuckDB: filter in SQL (good)
df = duckdb.sql("SELECT * FROM 'data.csv' WHERE amount > 100").df()

5. Select only needed columns

If your CSV has 50 columns and you use only 3, do not load them all.

df = pl.read_csv("data.csv", columns=["category", "amount", "date"])

When to use each tool

Situation Tool
Data < 1 GB, pandas ecosystem pandas
Data 1-10 GB, one machine Polars (lazy) or DuckDB
Data > 10 GB, one machine DuckDB over Parquet
Data > RAM of one machine Dask or Spark
You know SQL DuckDB
Need pandas compatibility pandas 2.0 with Arrow backend

Practical rule: start with DuckDB. If you need complex DataFrames, use Polars. If you need the pandas ecosystem (scikit-learn, matplotlib), use pandas with Arrow backend.


Code: full analysis with Polars and DuckDB

Polars (lazy)

import polars as pl

result = (
    pl.scan_parquet("sales.parquet")
    .filter(pl.col("date") >= "2024-01-01")
    .group_by("region", "product")
    .agg(
        pl.col("revenue").sum().alias("total_revenue"),
        pl.col("quantity").sum().alias("total_qty"),
        pl.col("revenue").mean().alias("avg_revenue"),
    )
    .sort("total_revenue", descending=True)
    .collect()
)
print(result.head(10))

DuckDB (SQL)

import duckdb

result = duckdb.sql("""
    SELECT region, product,
           SUM(revenue) AS total_revenue,
           SUM(quantity) AS total_qty,
           AVG(revenue) AS avg_revenue
    FROM 'sales.parquet'
    WHERE date >= '2024-01-01'
    GROUP BY region, product
    ORDER BY total_revenue DESC
    LIMIT 10
""").df()
print(result)

Both run in seconds over gigabytes of data with MB of RAM.


Common mistakes

  1. Loading everything into pandas and filtering after. Filter during read.
  2. Using CSV for large datasets. Convert to Parquet once.
  3. Not specifying data types. pandas infers int64 for everything. Use dtype or Arrow to reduce memory.
  4. Joining without filtering first. A join of two large tables multiplies memory consumption. Filter before joining.
  5. Ignoring Polars lazy mode. If you use pl.read_csv instead of pl.scan_csv, you lose optimization.
  6. Not measuring memory. Use df.estimated_size() (Polars) or df.memory_usage() (pandas) to know consumption.

Checklist before analyzing large data

  • The file is in Parquet, not CSV.
  • Only needed columns are loaded.
  • Filtering happens during read, not after.
  • Lazy mode (Polars) or SQL (DuckDB) is used when data does not fit in memory.
  • Execution time and memory consumption have been measured.
  • Data types are optimized (not everything int64).
  • Data has been filtered before joins.
  • The result has been verified against a small sample.

Analyzing large data is not having a more powerful machine. It is using the right tool for the scale. A jackhammer is not better than a hammer: it is different. And using a jackhammer to drive a nail is as inefficient as using a hammer to break concrete.