Skip to content

Lesson 43 of 59Libraries every Python developer knows

DataFrames with pandas and Polars

Load, filter, group, join and clean tabular data with pandas and Polars, use lazy queries, and know which library to pick.

19 min read0/4 questions

A lot of backend work is really table work: a CSV export from finance, a nightly report, an import from a partner, a quick answer to "which customers stopped ordering last month?". You can do all of it with loops and dictionaries, but it is slow to write and easy to get wrong. A DataFrame is a table in memory with named, typed columns and a vocabulary of operations (filter, group, join) that maps directly onto how you think about the data. pandas is the long-standing standard. Polars is the fast, modern alternative many teams now reach for. This lesson teaches both side by side.

What the libraries save you

Start with the problem. Here is "total revenue and order count per city, for paid orders only" with the standard library:

Pythonby_hand.py
import csvimport iofrom collections import defaultdict data = """order_id,city,amount,status1,Oslo,120.0,paid2,Rome,80.5,paid3,Oslo,,refunded4,Lima,42.0,paid5,Rome,200.0,paid6,Oslo,15.25,paid""" totals = defaultdict(float)counts = defaultdict(int) for row in csv.DictReader(io.StringIO(data)): if row["status"] != "paid": continue if not row["amount"]: # missing value: skip it, by hand continue amount = float(row["amount"]) # everything in a CSV is text, convert by hand totals[row["city"]] += amount counts[row["city"]] += 1 for city in sorted(totals, key=totals.get, reverse=True): print(f"{city:<5} total={totals[city]:>7.2f} orders={counts[city]}")
Output
Press Run (⌘ Enter) to see what happens.

It works, but you handled type conversion, missing values, grouping and sorting yourself, and every new question means another loop. With a DataFrame the same thing is one readable expression, and it runs in compiled code instead of a Python loop.

pandas basics

Install with uv add pandas (add pyarrow too if you will read Parquet). A DataFrame is a set of columns; each column is a Series, backed by a NumPy-style array.

report.py
import pandas as pd
 
orders = pd.read_csv("orders.csv")          # types are inferred: amount becomes float64
users = pd.read_parquet("users.parquet")    # Parquet stores types and is much faster
 
orders.head()          # first 5 rows
orders.info()          # columns, dtypes, non-null counts
orders.describe()      # quick statistics for number columns
orders.shape           # (rows, columns)

Selecting and filtering:

orders["amount"]                         # one column, a Series
orders[["city", "amount"]]               # several columns, a DataFrame
paid = orders[orders["status"] == "paid"]                  # boolean mask, like NumPy
big = orders.loc[orders["amount"] > 100, ["order_id", "city"]]   # rows and columns at once
orders["amount_eur"] = orders["amount"] * 0.92             # a new column, vectorised

.loc[rows, columns] selects by labels and masks. Use it whenever you assign to a filtered subset, for example orders.loc[orders["city"] == "Oslo", "region"] = "north". Chained indexing like orders[mask]["region"] = ... writes into a temporary copy, so your table does not change. Older pandas versions warn with SettingWithCopyWarning; with copy-on-write behaviour in newer versions it simply never updates the original.

Grouping and aggregating is where pandas pays for itself. Named aggregation gives clear output columns:

summary = (
    orders[orders["status"] == "paid"]
    .groupby("city", as_index=False)
    .agg(total=("amount", "sum"), orders=("order_id", "count"))
    .sort_values("total", ascending=False)
)

Joins combine tables on a key, like SQL:

enriched = orders.merge(users, on="user_id", how="left")   # keep every order

how="inner" keeps only matching rows, "left" keeps every row from the left table and fills gaps with missing values. Pass validate="many_to_one" to make pandas raise if the right table unexpectedly has duplicate keys, which would otherwise multiply your rows quietly.

Quick check
orders has 1,000 rows. You run orders.merge(users, on="user_id", how="left") and get 1,030 rows. What is the most likely cause?
Need a nudge? A hint rules out a wrong answer.

Missing data

Real data has holes. pandas marks them as NaN (or NA/NaT for some types).

orders["amount"].isna().sum()             # how many are missing
orders.dropna(subset=["amount"])          # drop rows missing an amount
orders.fillna({"amount": 0, "city": "unknown"})

Most aggregations skip missing values: sum treats them as nothing, count only counts present values, and mean averages what is there. That is usually what you want, but decide on purpose. A missing amount on a refunded order and a missing amount from a broken import mean different things.

One classic surprise: an integer column with a missing value becomes float64 in pandas by default, because NumPy integers cannot hold NaN. pandas has nullable types ("Int64", with a capital I) and Arrow-backed types to fix this; Polars has nulls in every type from the start.

Dates and time

Reports are usually "per day" or "per month", so parse dates when you load the file. A date stored as text cannot be compared, grouped by month or subtracted.

orders = pd.read_csv("orders.csv", parse_dates=["created_at"])
orders["month"] = orders["created_at"].dt.to_period("M")
monthly = orders.groupby("month")["amount"].sum()
 
recent = orders[orders["created_at"] >= "2026-01-01"]   # strings compare against datetimes

The .dt accessor gives you .year, .month, .day_name() and more on a datetime column, and .str does the same for text columns (orders["city"].str.lower()). Store timestamps in UTC and convert to a local time zone only for display, exactly as you would in your API.

Polars: expressions and speed

Polars (uv add polars) is written in Rust, uses all your CPU cores, and is built on the Arrow columnar format. Its API is designed around expressions: small descriptions of a column computation, built with pl.col(...), that Polars can optimise and run in parallel.

report_polars.py
import polars as pl
 
orders = pl.read_csv("orders.csv")
 
summary = (
    orders
    .filter(pl.col("status") == "paid")
    .group_by("city")
    .agg(
        pl.col("amount").sum().alias("total"),
        pl.len().alias("orders"),
    )
    .sort("total", descending=True)
)

The core methods each take expressions:

PolarsDoespandas rough equivalent
df.select(...)Pick or compute columnsdf[["a", "b"]]
df.with_columns(...)Add or replace columnsdf["c"] = ...
df.filter(...)Keep matching rowsdf[mask]
df.group_by(...).agg(...)Group and aggregatedf.groupby(...).agg(...)
df.join(other, on=..., how=...)Combine tablesdf.merge(...)
df.sort(...)Order rowsdf.sort_values(...)
orders = orders.with_columns(
    (pl.col("amount") * 0.92).alias("amount_eur"),
    pl.col("city").str.to_uppercase(),
)
orders.join(users, on="user_id", how="left")
orders.drop_nulls("amount")
orders.with_columns(pl.col("amount").fill_null(0))

There is no index in Polars and no chained-assignment trap: every method returns a new DataFrame. Missing values are always null, in any type. group_by does not promise an output order, so sort the result (or pass maintain_order=True) when order matters.

Lazy queries

Polars' biggest advantage appears in lazy mode. pl.scan_csv (or pl.scan_parquet) does not read anything. It returns a LazyFrame that records your steps as a plan. Only .collect() runs it, after the query optimiser has rewritten the plan.

lazy_report.py
summary = (
    pl.scan_parquet("orders/*.parquet")
    .filter(pl.col("status") == "paid")
    .group_by("city")
    .agg(pl.col("amount").sum().alias("total"))
    .collect()
)
What happens when you call collect()
scan_parquet: 40 columns, 50M rowsscan_parquet40 columns, 50M rowsQuery plan: filter, group, aggQuery planfilter, group, aggOptimiser: pushdown, pruningOptimiserpushdown, pruningReader: 3 columns, paid onlyReader3 columns, paid onlyDataFrame: one row per cityDataFrameone row per citylazy stepscollect()smaller planparallel run

scan_parquet, filter, group_by and agg read nothing. They only record steps in a plan.

1/4

Call .explain() on a LazyFrame to print the optimised plan. For files bigger than memory, Polars can also run the plan in a streaming mode that processes the data in chunks; check the docs for the current way to enable it.

Predict the outputPython

What does this print? (orders.csv exists and has 1 million rows.)

lf = pl.scan_csv("orders.csv").filter(pl.col("amount") > 100)
print(type(lf).__name__)
Need a nudge? Hints walk you through it.
Match the pairs0/5 matched

Match each pandas operation to its Polars equivalent.

Choose an item, then its match on the other side.

Which one should you choose?

Choose pandas when you are joining an existing pandas codebase, need a library that only accepts pandas objects (many plotting, stats and ML tools), or are exploring data in a notebook where its huge ecosystem of answers helps. Nearly every data role expects you to read pandas code.

Choose Polars when you are starting fresh, data is large (hundreds of megabytes and up), speed and memory matter, or you are building a pipeline that runs every night. Expressions also tend to produce clearer, less buggy code than long chains of pandas indexing.

They work together: pl.from_pandas(df) and polars_df.to_pandas() convert between them, cheaply when both use Arrow types.

Both also read straight from a database. pd.read_sql(query, engine) takes a SQLAlchemy engine, and Polars has pl.read_database for the same job. That is handy for reports, but let the database do the filtering and grouping in the query, and pull only the result.

Performance tips for either:

  • Never loop over rows. iterrows() in pandas and Python loops over Polars rows throw away the speed. Express the work as column operations.
  • Use Parquet instead of CSV for anything you store yourself. It keeps types, compresses well, and lets readers skip columns.
  • Read less. usecols= in pd.read_csv, or lazy scans in Polars, so unused columns never load.
  • Use the right types. Turn repeated strings like country names into categoricals; parse dates once at load time.
  • Push work to the database when the data already lives there. A GROUP BY in Postgres beats downloading a million rows to group in Python.
Put it in order6 steps

Order a sensible nightly reporting job written with Polars.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
DataFrame
An in-memory table with named, typed columns and operations like filter, group and join.
Series
A single pandas column: a typed array with an index.
groupby / group_by
Split rows by a key, aggregate each group, and combine the results into one table.
left join
Keep every row of the left table, adding matching columns from the right where they exist.
expression
A Polars description of a column computation, like pl.col("amount").sum(), that the engine can optimise.
lazy query
A recorded plan that runs only on .collect(), letting the optimiser rewrite it first.
Parquet
A compressed, columnar file format that stores types and lets readers skip unused columns.