DEV Community

Cover image for Build a Fast Data Pipeline with Polars
Muhammad Saud
Muhammad Saud

Posted on Originally published at logicstack.org

Build a Fast Data Pipeline with Polars

Polars is a DataFrame library for Python with its query engine written in Rust. It reads data lazily, plans the whole query before it runs, and uses every CPU core. In this tutorial we build a complete sales pipeline with it: one million orders filtered, joined and grouped in under a second, with the result saved as Parquet.

Key takeaways

  • Polars builds a lazy query plan first and runs it only when we call .collect(), so it can push filters and column choices down into the file scan.
  • One pipeline can filter, add a calculated column, join a second table and group the result, all in a single readable chain.
  • On our test machine, Polars grouped one million rows in 0.23 seconds against 1.00 seconds for pandas, a 4.4x gap that grows with data size.
  • Writing the result to Parquet keeps types and shrinks the file, so the summary is ready for the next tool in the chain.
  • Streaming mode processes data in chunks, so a file larger than memory still runs on an ordinary laptop.

What we build

We build a sales pipeline that answers one question: which region, category and customer segment earned the most revenue in the second half of 2026? It reads a CSV of one million orders, keeps only July to December rows, works out the revenue of each order, joins a customers table to add the segment, groups by region, category and segment, and saves the 36 row summary as a Parquet file. We then time the same group by in pandas, so the speed claim here comes from a run on our own machine, not a marketing page.

Prerequisites

We need Python 3.12 and pip, then one install: pip install polars pandas numpy. We ran this tutorial with Polars 2.2.0, pandas 3.1.1 and NumPy 2.5.5 on Python 3.12.3. Polars 2.2.0 was released on 24 November 2026, so it is current at the time of writing, according to the Plotly engineering blog. No database and no cloud account are needed.

Step 1: Create the dataset

Real sales data is private, so we generate our own: one million orders across ten products, four regions and three customer segments. A fixed seed keeps the data identical on every run, which matters when we compare timings later.

import numpy as np
import polars as pl

rng = np.random.default_rng(42)
N = 1_000_000
# (product, category, base price)
products = [
    ("Laptop", "Electronics", 899.0), ("Headphones", "Electronics", 79.0),
    ("Keyboard", "Electronics", 49.0), ("Desk Chair", "Furniture", 199.0),
    ("Standing Desk", "Furniture", 349.0), ("Notebook", "Stationery", 12.0),
    ("Pen Set", "Stationery", 18.0), ("Monitor", "Electronics", 249.0),
    ("Bookshelf", "Furniture", 129.0), ("Mouse", "Electronics", 29.0),
]
names = [p[0] for p in products]
cats = [p[1] for p in products]
prices = np.array([p[2] for p in products])
idx = rng.integers(0, len(names), N)
regions = np.array(["North", "South", "East", "West"])
region = regions[rng.integers(0, 4, N)]
quantity = rng.integers(1, 6, N)
unit_price = np.round(prices[idx] * rng.uniform(0.9, 1.1, N), 2)
order_date = np.array(["2026-{:02d}-{:02d}".format(m, d)
    for m, d in zip(rng.integers(1, 13, N), rng.integers(1, 29, N))])

orders = pl.DataFrame({
    "order_id": np.arange(1, N + 1),
    "customer_id": rng.integers(1, 50_001, N),
    "product": np.array(names)[idx],
    "category": np.array(cats)[idx],
    "region": region,
    "quantity": quantity,
    "unit_price": unit_price,
    "order_date": order_date,
})
orders.write_csv("orders.csv")

customers = pl.DataFrame({
    "customer_id": np.arange(1, 50_001),
    "segment": np.array(["Consumer", "Corporate", "Home Office"])
        [rng.integers(0, 3, 50_000)],
    "country": np.array(["Pakistan", "UK", "Germany", "UAE"])
        [rng.integers(0, 4, 50_000)],
})
customers.write_csv("customers.csv")
Enter fullscreen mode Exit fullscreen mode

Running it prints the shape of what we made:

orders.csv: 1,000,000 rows, 8 columns
customers.csv: 50,000 rows
Enter fullscreen mode Exit fullscreen mode

The orders file is about 58 MB. That size is deliberate: big enough that a naive approach feels slow, small enough that the whole tutorial runs in seconds on a laptop.

Step 2: Build the lazy pipeline

We open both files with pl.scan_csv() instead of pl.read_csv(). The scan returns a LazyFrame, a description of a query rather than data. Nothing is read from disk until we call .collect(), and that delay is what lets Polars plan the whole job before it starts.

import polars as pl

orders = pl.scan_csv("orders.csv")
customers = pl.scan_csv("customers.csv")

result = (
    orders
    .filter(pl.col("order_date").str.slice(0, 7) >= "2026-07")
    .with_columns((pl.col("quantity") * pl.col("unit_price")).alias("revenue"))
    .join(customers, on="customer_id", how="left")
    .group_by(["region", "category", "segment"])
    .agg([
        pl.col("revenue").sum().alias("total_revenue"),
        pl.col("order_id").count().alias("orders"),
        pl.col("revenue").mean().alias("avg_order_value"),
    ])
    .sort("total_revenue", descending=True)
)

summary = result.collect()
print(summary.head(10))
print(f"Rows in summary: {summary.height}")
print(f"Total H2 revenue: ${summary['total_revenue'].sum():,.2f}")
Enter fullscreen mode Exit fullscreen mode

Each step does one clear job. The filter keeps only second half orders, with_columns adds a revenue column, the join adds the customer segment, the group by turns one million rows into 36 summary rows, and the sort puts the biggest earners first. Here is the real output from our run:

Rows in summary: 36
Total H2 revenue: $301,492,053.89
Enter fullscreen mode Exit fullscreen mode

The top five rows look like this:

South | Electronics | Consumer    | $16,569,396.63 | 21,095 orders | avg $785.47
West  | Electronics | Consumer    | $16,533,526.13 | 20,959 orders | avg $788.85
North | Electronics | Home Office | $16,494,552.38 | 20,908 orders | avg $788.91
East  | Electronics | Consumer    | $16,445,873.27 | 20,911 orders | avg $786.47
North | Electronics | Corporate   | $16,391,411.10 | 20,682 orders | avg $792.54
Enter fullscreen mode Exit fullscreen mode

Electronics leads every region, which is no surprise given the laptop price. The filter kept 499,431 of the million orders, so roughly half the year fell in the second half, as expected from uniform random dates.

Why is Polars faster than pandas?

Three design choices explain most of the gap. The query engine is written in Rust and runs without the Python global interpreter lock, so work spreads across all CPU cores. Data lives in the Apache Arrow columnar format, which keeps each column in one dense block of memory instead of a row of Python objects. And lazy execution lets the optimiser rewrite the plan before any data moves: it pushes filters into the file scan, drops columns we never use, and runs independent expressions in parallel. Pandas runs each step eagerly and mostly on one core. Pandas 3.0, released in January 2026, closed part of the gap with copy on write and a new string type, according to the Vertex Frontier benchmark roundup, but the lazy planning gap remains. Independent numbers back this up: in the DuckDB Labs db-benchmark, Polars ran the group by suite about 7x faster than pandas at 5 GB and the join suite about 40x faster, as summarised by Danilchenko in September 2026.

Step 3: Read the query plan

A lazy query can be inspected before it runs. Calling .explain() prints the plan Polars will execute, and it shows the optimiser at work. Two lines deserve attention. SELECTION sits inside the CSV scan, which means the date filter is applied while reading, so January to June rows never enter memory. PROJECT 7/8 COLUMNS means Polars reads only the seven columns the query needs and skips the product name entirely. These two rewrites are called predicate pushdown and projection pushdown, and they are free: we get them by writing the query lazily, not by hand tuning anything.

SORT BY [descending: [true]] [col("total_revenue")]
  AGGREGATE [col("revenue").sum(), col("order_id").count()]
    BY [col("region"), col("category"), col("segment")]
      LEFT JOIN ON: [col("customer_id")]
        WITH_COLUMNS: [(col("quantity") * col("unit_price")).alias("revenue")]
          Csv SCAN [orders.csv]
          PROJECT 7/8 COLUMNS
          SELECTION: (col("order_date").str.slice(0, 7) >= "2026-07")
Enter fullscreen mode Exit fullscreen mode

When a Polars pipeline is slow, .explain() is the first place we look.

Step 4: Save the result as Parquet

A CSV summary works, but Parquet is the better home for pipeline output. It stores types, compresses well, and lets the next tool read only the columns it needs. One line writes it, and reading it back returns the same types we wrote:

summary.write_parquet("revenue_summary.parquet")
df = pl.read_parquet("revenue_summary.parquet")
print(df.height)  # 36
Enter fullscreen mode Exit fullscreen mode

Our 36 row summary became a 3 KB Parquet file. A practical habit is to keep raw data as CSV or Parquet, do the work in Polars, and write each pipeline stage out as Parquet. Any stage can then be re-run or inspected without repeating the whole pipeline, and a downstream tool such as DuckDB can read the same file without conversion.

Step 5: Measure Polars against pandas

Speed claims need a local measurement, so we timed the same group by in both libraries on the same file and the same machine:

import time
import pandas as pd

def polars_groupby():
    return (pl.scan_csv("orders.csv")
        .with_columns((pl.col("quantity") * pl.col("unit_price")).alias("revenue"))
        .group_by("region").agg(pl.col("revenue").sum()).collect())

def pandas_groupby():
    df = pd.read_csv("orders.csv")
    df["revenue"] = df["quantity"] * df["unit_price"]
    return df.groupby("region")["revenue"].sum()

t0 = time.perf_counter(); polars_groupby(); t_pl = time.perf_counter() - t0
t0 = time.perf_counter(); pandas_groupby(); t_pd = time.perf_counter() - t0
print(f"Polars: {t_pl:.2f}s, pandas: {t_pd:.2f}s, speedup: {t_pd / t_pl:.1f}x")
Enter fullscreen mode Exit fullscreen mode

Our run, on a 4 core virtual machine with Polars 2.2.0 and pandas 3.1.1, printed this:

Polars (lazy scan + group-by): 0.23s
pandas (read_csv + group-by): 1.00s
Polars was 4.4x faster on this machine
Enter fullscreen mode Exit fullscreen mode

We should be honest about what this number means. At one million rows the gap is 4.4x, not 40x. The 40x join figures from the DuckDB Labs benchmark come from 5 GB of data, where pandas spends most of its time moving Python objects. On small data that fits comfortably in memory, pandas is fast enough and the gap is small. The honest rule is to measure on our own data size before rewriting a working pipeline. The Polars version is also shorter to write, and the lazy plan gives us the filter and column pruning for free, which is worth having even before speed enters the picture.

When should you stay with pandas?

Polars is not a drop in replacement, and the Polars documentation says so plainly. Stay with pandas when the data fits in memory and the rest of the stack expects pandas: scikit-learn, matplotlib and statsmodels all take pandas frames directly, while Polars needs a conversion at the boundary. Stay with pandas for heavy string work too, since pandas is often faster there on current versions, as the TildAlice 2026 benchmark notes. A good migration path is to change one slow stage first, usually the biggest read_csv or group by, and convert back to pandas at the end with .to_pandas().

Step 6: Stream data bigger than memory

Everything so far fits in memory. The last step covers the case where it does not. Polars can run a lazy query in streaming mode, processing the file in batches instead of loading it whole. We ask how many units each category sold in the North region:

streamed = (
    pl.scan_csv("orders.csv")
    .filter(pl.col("region") == "North")
    .group_by("category")
    .agg(pl.col("quantity").sum().alias("units_sold"))
    .collect(engine="streaming")
)
print(streamed)
Enter fullscreen mode Exit fullscreen mode

The output matches the eager result exactly:

Electronics | 373,491 units
Furniture   | 225,656 units
Stationery  | 150,516 units
Enter fullscreen mode Exit fullscreen mode

Streaming mode works for filters, group bys and joins that fit its rules, and it spills sorts and window functions to disk since Polars 2.0, according to the Vertex Frontier roundup. It is the right default when a file is larger than RAM, or when we simply do not want to find out the hard way. For files that do fit in memory, the normal .collect() is faster, so we choose per job, not per project.

What to try next

First, point the pipeline at a real file of our own, such as an export from a shop or a log file, and replace the generated columns with the real ones. The filter, join and group by pattern stays the same. Second, add a monthly revenue trend by grouping on pl.col("order_date").str.slice(0, 7), which reuses the same scan. Third, generate five million rows instead of one and run the Step 5 benchmark again, then watch how the Polars to pandas gap changes with size. That single experiment teaches more about when Polars pays off than any benchmark article can.


Originally published on LogicStack. Run the code examples right in your browser with our free interactive Python and SQL playgrounds — no setup, no sign-up.

Top comments (0)