Data Science Advanced

Polars vs pandas: Fast DataFrames with Apache Arrow and Lazy Queries

How the Arrow memory model, pandas 3 Copy-on-Write and Arrow dtypes, and Polars expressions and lazy query optimisation work in practice, with interop tips and an honest benchmark.

KC Ramo DjangoZen Team Dec 05, 2026 19 min read 4 views

pandas and Polars both give you a DataFrame, but they are built on different execution models. pandas runs each operation eagerly, one call at a time; Polars can also take a whole query, optimise it and run it on all cores. This tutorial looks at the Apache Arrow memory model both libraries now share, the pandas 3 changes you need to know (Copy-on-Write and Arrow-backed dtypes), and how Polars expressions and lazy queries work in practice. It ends with a benchmark that reports the numbers that favour pandas as well as the ones that favour Polars.

Setup and test data

Everything below was run with Python 3.13, Polars 2.2.0, pandas 3.1.2, PyArrow 26.0.1 and NumPy 2.5.5. Create a virtual environment and install the four packages:

python -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install "polars>=2.2,<3" "pandas>=3.1,<4" "pyarrow>=26,<27" "numpy>=2.5,<3"

We need data that is large enough to show real differences but generated locally, so the results are reproducible. The script below writes five million synthetic orders and 200,000 customers to Parquet with a fixed random seed. Timestamps are sorted, which matters later: Parquet stores min/max statistics per row group, and sorted data makes those statistics useful for skipping.

import numpy as np
import polars as pl

rng = np.random.default_rng(42)
n = 5_000_000

seconds = np.sort(rng.integers(0, 365 * 86_400, n))
orders = pl.DataFrame({
    "order_id": np.arange(n),
    "customer_id": rng.integers(1, 200_001, n),
    "country": rng.choice(["NL", "DE", "BE", "FR", "US"], n,
                          p=[0.30, 0.25, 0.15, 0.20, 0.10]),
    "amount": np.round(rng.gamma(2.0, 30.0, n), 2),
    "ts": (np.datetime64("2026-01-01T00:00:00", "us")
           + (seconds * 1_000_000).astype("timedelta64[us]")),
})
customers = pl.DataFrame({
    "customer_id": np.arange(1, 200_001),
    "segment": rng.choice(["consumer", "smb", "enterprise"], 200_000,
                          p=[0.70, 0.25, 0.05]),
})

orders.write_parquet("orders.parquet", row_group_size=500_000)
customers.write_parquet("customers.parquet")
print(orders.head(3))
shape: (3, 5)
┌──────────┬─────────────┬─────────┬────────┬─────────────────────┐
│ order_id ┆ customer_id ┆ country ┆ amount ┆ ts                  │
│ ---      ┆ ---         ┆ ---     ┆ ---    ┆ ---                 │
│ i64      ┆ i64         ┆ str     ┆ f64    ┆ datetime[μs]        │
╞══════════╪═════════════╪═════════╪════════╪═════════════════════╡
│ 0        ┆ 67779       ┆ NL      ┆ 115.47 ┆ 2026-01-01 00:00:00 │
│ 1        ┆ 182028      ┆ DE      ┆ 147.32 ┆ 2026-01-01 00:00:03 │
│ 2        ┆ 13316       ┆ US      ┆ 82.53  ┆ 2026-01-01 00:00:03 │
└──────────┴─────────────┴─────────┴────────┴─────────────────────┘

NumPy only converts datetime64 values with a D, ms, us or ns unit into Polars, which is why the timestamps are built in microseconds rather than seconds. The resulting file is about 53 MB.

The Arrow memory model

Apache Arrow is a specification for laying out tabular data in memory, column by column. Each column is one or more contiguous buffers:

  • A values buffer holding fixed-width values back to back (eight bytes per int64, for example).
  • A validity bitmap with one bit per row that marks nulls. A null integer is just a cleared bit, so the column stays int64. With classic NumPy-backed pandas a null forced an integer column to float64 and NaN.
  • For variable-length data such as strings, an offsets buffer pointing into one large data buffer instead of one Python object per value. Polars goes further and stores strings as string views: short strings are inlined in a 16-byte view, longer ones carry a prefix plus a pointer, which makes comparisons and slicing cheap.

Columns are grouped into record batches, and a table is a list of batches per column (a chunked array). Because the layout is standardised, two libraries in one process can hand each other a column by passing pointers to these buffers: "zero-copy" means only ownership changes hands. The Arrow PyCapsule interface (__arrow_c_stream__) makes this work between any libraries that implement it.

Parquet is the matching on-disk format: columnar, compressed, organised in row groups with per-column statistics. Reading it always involves decoding, but a reader can skip unneeded columns and row groups whose statistics rule them out.

pandas 3: Copy-on-Write and Arrow-backed dtypes

Copy-on-Write is the only mode

Since pandas 3.0, Copy-on-Write (CoW) is always enabled and cannot be switched off. Every indexing result behaves as a new object; underneath, data is shared until one side writes, and only then copied. Two consequences matter for existing code:

import pandas as pd

df = pd.DataFrame({"a": [1, 2, 3], "b": [10.0, 20.0, 30.0]})

sub = df[df["a"] > 1]
sub["b"] = 0.0             # modifies sub only, no SettingWithCopyWarning
print(df["b"].tolist())

s = df["a"]
s.iloc[0] = 100            # s gets its own copy at this point
print(df["a"].tolist())
[10.0, 20.0, 30.0]
[1, 2, 3]

Chained assignment such as df["b"][mask] = value now never updates df; pandas emits a ChainedAssignmentError warning and leaves the frame untouched. Use df.loc[mask, "b"] = value. The benefit is that methods like rename, reset_index or astype no longer copy eagerly, so method chains got cheaper. The old mode.copy_on_write option still exists but is deprecated and has no effect.

Arrow-backed dtypes

pandas 3 also infers a dedicated string dtype (str) for text columns. When PyArrow is installed, its storage is Arrow, so string columns no longer hold one Python object per row. Numeric columns still default to NumPy. You can ask for Arrow storage everywhere with dtype_backend="pyarrow":

orders_np = pd.read_parquet("orders.parquet")
orders_pa = pd.read_parquet("orders.parquet", dtype_backend="pyarrow")
print(orders_np.dtypes, orders_pa.dtypes, sep="\n\n")
print(pd.Series(["x"]).dtype.storage)

ints = pd.Series([1, None, 3], dtype="int64[pyarrow]")
print(ints.dtype, ints.sum(), pd.Series([1, None, 3]).dtype)
order_id                int64
customer_id             int64
country                   str
amount                float64
ts             datetime64[us]
dtype: object

order_id               int64[pyarrow]
customer_id            int64[pyarrow]
country         large_string[pyarrow]
amount                double[pyarrow]
ts             timestamp[us][pyarrow]
dtype: object
pyarrow
int64[pyarrow] 4 float64

The int64[pyarrow] series keeps its integers and a real null; the default constructor still turns [1, None, 3] into float64. Arrow dtypes give you correct nulls and cheaper interchange. They do not automatically make computation faster: many pandas operations are implemented for NumPy first, and some Arrow-backed paths convert internally. The benchmark later shows a case where the Arrow backend is slightly slower. Measure before converting a codebase.

Polars expressions

Polars has no index and no row-wise apply in the normal workflow. Instead, you describe computations with expressions: pl.col("amount").sum() is not a number but a recipe that Polars evaluates inside a context such as select, with_columns, filter or agg. Expressions in one context run in parallel.

orders = pl.read_parquet("orders.parquet")

summary = orders.select(
    pl.col("amount").sum().alias("revenue"),
    pl.col("customer_id").n_unique().alias("customers"),
    (pl.col("amount") > 100).mean().alias("share_over_100"),
)
print(summary)
shape: (1, 3)
┌──────────┬───────────┬────────────────┐
│ revenue  ┆ customers ┆ share_over_100 │
│ ---      ┆ ---       ┆ ---            │
│ f64      ┆ u32       ┆ f64            │
╞══════════╪═══════════╪════════════════╡
│ 3.0001e8 ┆ 200000    ┆ 0.1546108      │
└──────────┴───────────┴────────────────┘

Expressions compose. A filtered aggregation is just an expression with .filter() inside it, which replaces the pandas pattern of building a boolean column first and summing it:

daily = (
    orders
    .with_columns(pl.col("ts").dt.date().alias("day"))
    .group_by("country", "day")
    .agg(
        pl.len().alias("orders"),
        pl.col("amount").sum().round(2).alias("revenue"),
        pl.col("amount").filter(pl.col("amount") > 100).len().alias("big_orders"),
    )
    .sort("country", "day")
)
print(daily.head(3))
shape: (3, 5)
┌─────────┬────────────┬────────┬───────────┬────────────┐
│ country ┆ day        ┆ orders ┆ revenue   ┆ big_orders │
│ ---     ┆ ---        ┆ ---    ┆ ---       ┆ ---        │
│ str     ┆ date       ┆ u32    ┆ f64       ┆ u32        │
╞═════════╪════════════╪════════╪═══════════╪════════════╡
│ BE      ┆ 2026-01-01 ┆ 2069   ┆ 122109.42 ┆ 297        │
│ BE      ┆ 2026-01-02 ┆ 2019   ┆ 121292.84 ┆ 316        │
│ BE      ┆ 2026-01-03 ┆ 2044   ┆ 127469.89 ┆ 365        │
└─────────┴────────────┴────────┴───────────┴────────────┘

Note that group_by does not preserve the order of groups by default (it is faster that way). Sort explicitly, or pass maintain_order=True, when order matters.

Lazy frames and query optimisation

Everything above ran eagerly on a DataFrame. A LazyFrame records the operations as a logical plan and only executes when you call collect(). That gives the optimiser the whole query to work with. scan_parquet returns a lazy frame without reading any data:

lf = (
    pl.scan_parquet("orders.parquet")
    .filter(pl.col("country") == "NL")
    .filter(pl.col("ts") >= pl.datetime(2026, 7, 1))
    .group_by("customer_id")
    .agg(pl.col("amount").sum().alias("spend"))
    .sort("spend", descending=True)
    .head(5)
)
print(lf.explain(optimized=False))
SLICE[offset: 0, len: 5]
  SORT BY [descending: [true]] [col("spend")]
    AGGREGATE[maintain_order: false]
      [col("amount").sum().alias("spend")] BY [col("customer_id")]
      FROM
      FILTER col("ts") >= 2026-07-01 00:00:00
      FROM
        FILTER col("country") == "NL"
        FROM
          Parquet SCAN [orders.parquet]
          PROJECT */5 COLUMNS
          ESTIMATED ROWS: 5000000

Plans read from the bottom up. The unoptimised plan is exactly what we wrote: read all five columns, filter twice, aggregate, sort everything, take five. Now the optimised plan:

print(lf.explain())
print(lf.collect())
SORT BY [slice: (0, 5), dynamic_pred: ..., descending: [true]] [col("spend")]
  FILTER col("spend").dynamic_predicate()
  FROM
    AGGREGATE[maintain_order: false]
      [col("amount").sum().alias("spend")] BY [col("customer_id")]
      FROM
      simple π 2/2 ["customer_id", "amount"]
        Parquet SCAN [orders.parquet]
        PROJECT 4/5 COLUMNS
        SELECTION: (col("country") == "NL") & (col("ts") >= 2026-07-01 00:00:00)
        ESTIMATED ROWS: 5000000
shape: (5, 2)
┌─────────────┬─────────┐
│ customer_id ┆ spend   │
│ ---         ┆ ---     │
│ i64         ┆ f64     │
╞═════════════╪═════════╡
│ 168137      ┆ 1262.52 │
│ 68728       ┆ 1117.07 │
│ 142380      ┆ 1093.35 │
│ 196702      ┆ 1067.91 │
│ 45321       ┆ 1067.15 │
└─────────────┴─────────┘

Three optimisations are visible:

  • Projection pushdown: PROJECT 4/5 COLUMNS. order_id is never decoded. The two filter columns are dropped right after the scan (π 2/2), so the aggregation only sees what it needs.
  • Predicate pushdown: both filters were merged into one SELECTION evaluated by the Parquet reader. Because ts is sorted, the row-group statistics let the reader skip the first half of the year without decompressing it.
  • Slice pushdown into the sort: sort(...).head(5) became a top-k sort with a dynamic predicate that discards groups which cannot reach the top five. You can also write this directly with top_k(5, by="spend").

Other optimisations you will see in plans include common-subexpression elimination, simplification of expressions, and pushing filters through joins to the side they belong to. lf.show_graph() renders the same plan as a diagram if Graphviz is installed. (LazyFrame.profile() was removed in Polars 2.0, because its per-node timings were misleading under the streaming engine.)

Two practical rules follow. First, start pipelines with scan_* rather than read_* whenever the source is a file, so the optimiser can reach the reader. Second, call collect() once at the end instead of collecting intermediate results; every intermediate collect() is an optimisation boundary. Since Polars 2.0 the streaming engine, which processes the plan in batches, is the default for lazy queries; sink_parquet() goes one step further and writes a result to disk without ever materialising it in memory.

Joins and window expressions

Joins

Joins work on lazy frames too, so the optimiser can push filters and projections through them. Pass validate to make cardinality assumptions explicit; a duplicated key in customers would raise an error instead of silently multiplying rows:

orders_lf = pl.scan_parquet("orders.parquet")
customers_lf = pl.scan_parquet("customers.parquet")

by_segment = (
    orders_lf.join(customers_lf, on="customer_id", how="left", validate="m:1")
    .group_by("segment")
    .agg(
        pl.len().alias("orders"),
        pl.col("amount").mean().round(2).alias("avg_amount"),
    )
    .sort("segment")
    .collect()
)
print(by_segment)

enterprise = customers_lf.filter(pl.col("segment") == "enterprise")
print(orders_lf.join(enterprise, on="customer_id", how="semi")
      .select(pl.len()).collect().item())
shape: (3, 3)
┌────────────┬─────────┬────────────┐
│ segment    ┆ orders  ┆ avg_amount │
│ ---        ┆ ---     ┆ ---        │
│ str        ┆ u32     ┆ f64        │
╞════════════╪═════════╪════════════╡
│ consumer   ┆ 3508923 ┆ 60.01      │
│ enterprise ┆ 250668  ┆ 59.98      │
│ smb        ┆ 1240409 ┆ 60.0       │
└────────────┴─────────┴────────────┘
250668

A semi join keeps rows from the left that have a match and never duplicates them; anti keeps rows without a match. Both are clearer and cheaper than an inner join followed by de-duplication. For time-series alignment ("the most recent price at the time of each order") use join_asof; the DuckDB tutorial in this category covers the same pattern in SQL.

Window expressions with over()

In pandas, per-group values aligned to the original rows need groupby().transform(). In Polars, any expression becomes a window expression by adding .over(). With order_by you get ordered windows such as running totals without sorting the frame first:

history = (
    orders_lf
    .filter(pl.col("customer_id") == 42)
    .with_columns(
        pl.col("amount").sum().over("country").alias("country_total"),
        pl.col("amount").cum_sum().over("country", order_by="ts")
            .alias("running_total"),
        pl.col("amount").rank("dense", descending=True).over("country")
            .alias("rank_in_country"),
    )
    .select("country", "ts", "amount", "running_total", "rank_in_country")
    .sort("country", "ts")
    .head(4)
    .collect()
)
print(history)
shape: (4, 5)
┌─────────┬─────────────────────┬────────┬───────────────┬─────────────────┐
│ country ┆ ts                  ┆ amount ┆ running_total ┆ rank_in_country │
│ ---     ┆ ---                 ┆ ---    ┆ ---           ┆ ---             │
│ str     ┆ datetime[μs]        ┆ f64    ┆ f64           ┆ u32             │
╞═════════╪═════════════════════╪════════╪═══════════════╪═════════════════╡
│ BE      ┆ 2026-08-01 05:07:04 ┆ 37.05  ┆ 37.05         ┆ 1               │
│ BE      ┆ 2026-10-12 21:34:28 ┆ 20.39  ┆ 57.44         ┆ 2               │
│ DE      ┆ 2026-08-24 22:12:33 ┆ 97.29  ┆ 97.29         ┆ 1               │
│ DE      ┆ 2026-08-26 12:58:27 ┆ 27.08  ┆ 124.37        ┆ 4               │
└─────────┴─────────────────────┴────────┴───────────────┴─────────────────┘

A window expression inside filter gives you "top N per group" in one step, the equivalent of SQL's QUALIFY:

top2 = (
    orders_lf
    .filter(pl.col("amount").rank("ordinal", descending=True).over("country") <= 2)
    .select("country", "order_id", "amount")
    .sort("country", "amount", descending=[False, True])
    .collect()
)
print(top2.head(4))
shape: (4, 3)
┌─────────┬──────────┬────────┐
│ country ┆ order_id ┆ amount │
│ ---     ┆ ---      ┆ ---    │
│ str     ┆ i64      ┆ f64    │
╞═════════╪══════════╪════════╡
│ BE      ┆ 1280965  ┆ 560.06 │
│ BE      ┆ 4728755  ┆ 476.01 │
│ DE      ┆ 1009979  ┆ 470.83 │
│ DE      ┆ 4945485  ┆ 459.59 │
└─────────┴──────────┴────────┘

Interop: moving data between Polars, pandas and Arrow

Many projects use both libraries: Polars for heavy transformations, pandas for libraries that expect it. Conversions are cheap when both sides use Arrow memory, and copy when they cannot.

import pyarrow as pa

table = orders.to_arrow()                    # Polars -> pyarrow.Table
again = pl.from_arrow(table)                 # pyarrow -> Polars

pdf_arrow = orders.to_pandas(use_pyarrow_extension_array=True)
pdf_numpy = orders.to_pandas()
print(pdf_arrow.dtypes["amount"], pdf_numpy.dtypes["amount"])

back = pl.from_pandas(pdf_arrow)             # pandas -> Polars
print(back.schema == orders.schema)

# Any object with __arrow_c_stream__ can be consumed directly
print(pa.table(orders).num_rows, pl.DataFrame(pdf_arrow).shape)
double[pyarrow] float64
True
5000000 (5000000, 5)

What actually copies:

  • to_arrow() and pl.from_arrow() share numeric buffers. Strings are converted between Polars' string-view layout and Arrow large_string, which is a conversion, not a free hand-over.
  • to_pandas(use_pyarrow_extension_array=True) keeps Arrow memory in pandas. Plain to_pandas() converts to NumPy; numeric columns without nulls can be shared, but a nullable integer column becomes float64 and is copied.
  • A NumPy view of a Polars column is only possible for numeric data without nulls. Ask for it explicitly and Polars raises instead of copying silently:
view = orders["amount"].to_numpy(allow_copy=False)   # zero-copy, read-only
print(view.flags["WRITEABLE"])
try:
    orders["country"].to_numpy(allow_copy=False)
except RuntimeError as exc:
    print(exc)
False
copy not allowed: cannot convert to a NumPy array without copying data

Convert at the boundary, once. A pipeline that goes Polars, pandas, Polars inside a loop pays the string conversion every time and loses the lazy optimiser at every hop.

A benchmark, done honestly

Many published benchmarks compare an optimised query with a naive one, or report a single run. The script below tries to avoid that:

  • Every function is called once as a warm-up (the Parquet file is then in the OS page cache for all contestants), followed by seven timed runs; the median and minimum are reported.
  • Query A measures end to end, from file to answer. pandas gets two versions: the obvious one, and one that uses the column and filter pushdown that read_parquet already supports through PyArrow.
  • Query B measures pure in-memory work on data that is already loaded, with both pandas backends.
  • The script checks that the libraries return the same answer.

The benchmark reuses orders, orders_np and orders_pa from the earlier sections, so save all snippets of this tutorial in order as bench.py and run it as one script.

import os
import statistics
import time

def bench(label, fn, repeat=7):
    fn()  # warm-up: page cache, lazy imports, thread pool start-up
    times = []
    for _ in range(repeat):
        t0 = time.perf_counter()
        fn()
        times.append(time.perf_counter() - t0)
    print(f"{label:<30} median {statistics.median(times) * 1000:6.0f} ms"
          f"  min {min(times) * 1000:6.0f} ms")

def pandas_a():
    df = pd.read_parquet("orders.parquet")
    df = df[(df["country"] == "NL") & (df["ts"] >= "2026-07-01")]
    return df.groupby("customer_id")["amount"].sum().nlargest(5)

def pandas_a_pushdown():
    df = pd.read_parquet(
        "orders.parquet",
        columns=["customer_id", "amount"],
        filters=[("country", "==", "NL"),
                 ("ts", ">=", pd.Timestamp("2026-07-01"))],
    )
    return df.groupby("customer_id")["amount"].sum().nlargest(5)

def polars_a():
    return (
        pl.scan_parquet("orders.parquet")
        .filter(pl.col("country") == "NL", pl.col("ts") >= pl.datetime(2026, 7, 1))
        .group_by("customer_id")
        .agg(pl.col("amount").sum())
        .top_k(5, by="amount")
        .collect()
    )

def pandas_b(df):
    return (
        df.assign(month=df["ts"].dt.month)
        .groupby(["country", "month"], observed=True)
        .agg(orders=("order_id", "size"), revenue=("amount", "sum"),
             customers=("customer_id", "nunique"))
    )

def polars_b(df):
    return (
        df.group_by("country", pl.col("ts").dt.month().alias("month"))
        .agg(pl.len().alias("orders"), pl.col("amount").sum().alias("revenue"),
             pl.col("customer_id").n_unique().alias("customers"))
    )

print(f"logical cores: {os.cpu_count()}, polars threads: {pl.thread_pool_size()}")
bench("A pandas, read everything", pandas_a)
bench("A pandas, pushdown", pandas_a_pushdown)
bench("A polars, lazy scan", polars_a)
bench("B pandas, numpy dtypes", lambda: pandas_b(orders_np))
bench("B pandas, pyarrow dtypes", lambda: pandas_b(orders_pa))
bench("B polars, eager", lambda: polars_b(orders))

assert pandas_a().round(2).tolist() == polars_a()["amount"].round(2).to_list()

Results on an 8-core, 16-thread laptop CPU with an NVMe drive:

logical cores: 16, polars threads: 16
A pandas, read everything      median    319 ms  min    292 ms
A pandas, pushdown             median    132 ms  min    107 ms
A polars, lazy scan            median     39 ms  min     36 ms
B pandas, numpy dtypes         median    854 ms  min    815 ms
B pandas, pyarrow dtypes       median   1293 ms  min   1120 ms
B polars, eager                median    141 ms  min    141 ms

Polars runs its own operators on every core by default, while pandas runs its operators on one (PyArrow's Parquet reader, used by both pandas functions in query A, is multithreaded). The fair follow-up is to limit Polars to a single thread. The variable must be set before Polars is imported:

POLARS_MAX_THREADS=1 python bench.py
logical cores: 16, polars threads: 1
A pandas, read everything      median    306 ms  min    258 ms
A pandas, pushdown             median    105 ms  min     98 ms
A polars, lazy scan            median    115 ms  min    109 ms
B pandas, numpy dtypes         median    833 ms  min    778 ms
B pandas, pyarrow dtypes       median   1044 ms  min   1016 ms
B polars, eager                median    265 ms  min    249 ms

How to read this:

  • Half of the gap in query A is not "Polars versus pandas" but "reading what you need versus reading everything". pandas with columns and filters is two to three times faster than naive pandas, and single-threaded Polars lands in the same range as that version. The remaining factor of about three comes from parallelism.
  • Query B is dominated by nunique per group, which is a known slow path in pandas. Single-threaded Polars is still about three times faster there; with all cores, about six times.
  • Arrow-backed pandas was slower for this workload. Arrow dtypes are about correctness and interchange first.
  • Noise is real: an earlier run of the same query on the same machine measured 1227 ms instead of 854 ms for the NumPy-backed pandas line in query B. Report medians of several runs, and repeat the whole script before trusting a difference smaller than about 1.5x.
  • All runs used warm caches. On a cold cache or network storage, I/O dominates and the libraries move closer together, except where pushdown lets one of them read less.

Your numbers will differ with hardware, data shape and query. Run the script on your own data before deciding anything.

When to choose which

SituationBetter fitWhy
Batch transformations over Parquet files of hundreds of MB or morePolars (lazy)Pushdown, parallel execution, streaming engine
Interactive analysis feeding scikit-learn, statsmodels, seabornpandas, or Polars converted at the endEcosystem still expects pandas or NumPy
Label-based alignment, MultiIndex, resampling of indexed time seriespandasPolars deliberately has no index
Long pipelines in production jobsPolarsStrict schema, explicit expressions, fewer silent dtype changes
Existing pandas codebase that workspandas 3Migrate for CoW correctness first; rewrite only hot spots

The two are not mutually exclusive. A common split is Polars for the extract-and-aggregate stage and pandas for the last mile, with a single Arrow-backed conversion in between.

Pitfalls when moving from pandas to Polars

  • No index. df.loc["2026-03"] has no equivalent; filter on a column. Results do not align on labels, they align on position or on explicit join keys.
  • Strict types. Polars refuses to compare a string column with an integer or to concatenate frames with different schemas unless you cast. This catches bugs that pandas would hide as object columns.
  • Python functions are a performance cliff. map_elements runs Python per row and blocks parallelism. Look for a native expression first.
  • Group order. group_by output order is not stable unless requested. Tests that compare frames should sort first or use polars.testing.assert_frame_equal with check_row_order=False.
  • Nulls versus NaN. Polars distinguishes missing values (null) from floating point NaN. fill_null does not touch NaN; use fill_nan for that.

Exercises

  1. Run lf.explain() on a query that filters on amount instead of ts. The predicate is still pushed into the scan, but the row-group statistics cannot skip anything. Measure the difference in runtime and explain it.
  2. Rewrite query B in pandas using dtype_backend="pyarrow" and a categorical country column. Does either change help? Keep the benchmark harness unchanged.
  3. Use join_asof to attach a monthly price list to each order, then check with validate and a row count that no orders were dropped or duplicated.
  4. Convert a five-million-row Polars frame to pandas with and without use_pyarrow_extension_array=True and time both. Add a nullable integer column and repeat.
  5. Write a lazy pipeline that ends in sink_parquet() and run it with POLARS_MAX_THREADS=2. Compare peak memory with an equivalent read_parquet pipeline.

Found a mistake in this tutorial? Let us know and we will fix it.