Data analysis · Beginner · 18 min
Get started with Polars expressions and lazy queries
By Padding · Updated 18 Nov 2026
python:3.15-slim (Debian 13) · Python 3.15 · Polars 2.2.0 · pandas 3.1.1 · pyarrow 26.0.1
You will load a shop's orders into Polars 2.2, filter, add columns, group and join them with expressions, then rerun the same report as a lazy query and read the plan Polars optimised.
On this page
Polars is a DataFrame library for Python written in Rust. It reads the same CSV and Parquet files as pandas, but you work with it differently. You describe each calculation as an expression, such as pl.col("quantity") * pl.col("unit_price"), and hand it to a context (select, filter, with_columns or group_by().agg()) that decides what to do with the result. Polars can then run independent expressions in parallel across your CPU cores, and in lazy mode it can rewrite the whole query before reading a single row.
In this tutorial you build a small sales report for a grocery chain with branches in Lagos, Abuja and Kano. You read the orders, filter them, add revenue and a size label, total them per branch, join a product list to get categories, and then rewrite the report as a lazy query and read the plan Polars produced. Along the way you meet the two habits that trip up people coming from pandas: Polars has no row index, and it refuses to mix types silently.
Everything lives in a throwaway folder, ~/polars-demo, which you delete at the end.
Step 1 · Create the project and the sample files
Make the folder and add Polars, plus pandas and pyarrow for the last step, where you hand a result to pandas. Each range allows patch releases only, so a new minor version cannot change behaviour under you:
mkdir -p ~/polars-demo
cd ~/polars-demo
uv init --no-package --python 3.15
uv add "polars>=2.2,<2.3" "pandas>=3.1,<3.2" "pyarrow>=26,<27"
uv run python -c "import polars, pandas, pyarrow; print(polars.__version__, pandas.__version__, pyarrow.__version__)"Now write the two data files. orders.csv holds twelve orders in naira from the first week of October. products.csv maps each product code to a name and a category. The product codes start with a zero on purpose: codes, phone numbers and account numbers look like numbers but are labels, and you will see what Polars does with them.
cd ~/polars-demo
cat > orders.csv <<'CSV'
order_id,order_date,branch,product_code,quantity,unit_price,payment
1001,2026-10-01,Lagos,0101,3,9500,card
1002,2026-10-01,Abuja,0204,2,3200,transfer
1003,2026-10-02,Lagos,0102,5,2800,cash
1004,2026-10-02,Kano,0301,6,1500,transfer
1005,2026-10-03,Abuja,0201,4,2400,transfer
1006,2026-10-03,Lagos,0101,1,9500,transfer
1007,2026-10-04,Kano,0302,10,700,cash
1008,2026-10-04,Abuja,0204,1,3200,card
1009,2026-10-05,Lagos,0102,2,2800,card
1010,2026-10-05,Kano,0301,3,1500,transfer
1011,2026-10-06,Abuja,0201,6,2400,cash
1012,2026-10-06,Lagos,0103,4,1800,transfer
CSV
cat > products.csv <<'CSV'
product_code,product,category
0101,Rice 5kg,Grains
0102,Palm oil 1L,Cooking
0103,Beans 1kg,Grains
0201,Maize flour 2kg,Grains
0204,Tea 500g,Drinks
0301,Gari 1kg,Grains
0302,Tomato paste,Cooking
CSV
wc -l orders.csv products.csvCheck it worked
The version line prints 2.2.0 3.1.1 26.0.1, or later patch releases. wc -l reports 13 orders.csv and 8 products.csv: a header line plus twelve orders and seven products.
Step 2 · Read the CSV and check its types
Start with a plain read and look at what Polars guessed. Create first_look.py:
cd ~/polars-demo
cat > first_look.py <<'PY'
import polars as pl
orders = pl.read_csv("orders.csv")
print(orders.head(3))
print(orders.schema)
PY
uv run first_look.pyThe table prints with its shape on top and each column's type under its name. Two guesses are wrong for this data. product_code came back as i64, so 0101 is now the number 101. order_date is str, so you cannot sort by month or take the weekday. Also notice what is missing: there is no index column down the left. A Polars DataFrame is just its columns, and rows are found by their values, never by a label. You will not need reset_index anywhere in this tutorial.
Fix both guesses at read time. schema_overrides sets the type of named columns, and try_parse_dates=True turns ISO dates such as 2026-10-01 into a date column. Put the read in load.py, so every later script loads the files the same way:
cd ~/polars-demo
cat > load.py <<'PY'
import polars as pl
def load_orders():
return pl.read_csv(
"orders.csv",
schema_overrides={"product_code": pl.String},
try_parse_dates=True,
)
def load_products():
return pl.read_csv("products.csv", schema_overrides={"product_code": pl.String})
if __name__ == "__main__":
orders = load_orders()
print(orders.head(3))
print(orders.schema)
print("rows:", orders.height, "columns:", orders.width)
PY
uv run load.pyCheck it worked
first_look.py shows 101 in the product_code column and str under order_date. load.py shows 0101 with its zero, str under product_code, date under order_date, and ends with rows: 12 columns: 7.
Step 3 · Select columns and filter rows with expressions
pl.col("branch") does not hold any data. It is a description: "the column called branch". Comparing it with == "Lagos" gives another description, "true where branch is Lagos". Nothing runs until you pass the expression to a context. select keeps the columns or expressions you name, and filter keeps the rows where an expression is true. Combine conditions with & (and) and | (or), with each condition in brackets. Create explore.py:
cd ~/polars-demo
cat > explore.py <<'PY'
import polars as pl
from load import load_orders
orders = load_orders()
print(orders.select("order_date", "branch", "quantity").head(4))
lagos_card = orders.filter(
(pl.col("branch") == "Lagos") & (pl.col("payment") == "card")
)
print(lagos_card)
large = orders.filter(pl.col("quantity") >= 5).select("order_id", "branch", "quantity")
print(large)
PY
uv run explore.pyA plain column name such as "branch" in select is shorthand for pl.col("branch"). You need the full form as soon as you do something with the column, such as compare it or multiply it.
Check it worked
The first table has three columns and four rows. The Lagos card table has two rows, orders 1001 and 1009. The last table lists the four orders of five units or more: 1003, 1004, 1007 and 1011.
Step 4 · Add columns with with_columns
with_columns keeps every existing column and adds (or replaces) the ones you give it. Name each new column with a keyword argument. Here you add revenue, the weekday, and a size label that uses pl.when().then().otherwise(), the Polars version of an IF formula in a spreadsheet. Create add_columns.py:
cd ~/polars-demo
cat > add_columns.py <<'PY'
import polars as pl
from load import load_orders
orders = load_orders().with_columns(
revenue=pl.col("quantity") * pl.col("unit_price"),
weekday=pl.col("order_date").dt.strftime("%a"),
size=pl.when(pl.col("quantity") >= 5).then(pl.lit("bulk")).otherwise(pl.lit("single")),
)
print(orders.select("order_id", "quantity", "unit_price", "revenue", "weekday", "size"))
print("total revenue:", orders["revenue"].sum())
PY
uv run add_columns.pyThe three new columns are computed from the original columns, not from each other, so Polars is free to work them out at the same time. If one new column needs another, chain a second .with_columns(...) after the first.
DataFrames in Polars are not changed in place. with_columns returns a new frame, which is why the result is assigned to orders. Writing orders.with_columns(...) on its own line and ignoring the result does nothing.
Check it worked
The table header says shape: (12, 6). Polars prints the first and last five rows with a … row in between, so you see revenue filled in (order 1001 is 28500), weekday showing Thu for 1 October 2026, and size set to bulk on orders such as 1003 and 1011. The last line reads total revenue: 118900.
Step 5 · Group and summarise with group_by and agg
group_by splits the rows by one or more columns, and agg takes expressions that each reduce a group to one value. pl.len() counts the rows in each group. Create summarise.py:
cd ~/polars-demo
cat > summarise.py <<'PY'
import polars as pl
from load import load_orders
orders = load_orders().with_columns(revenue=pl.col("quantity") * pl.col("unit_price"))
by_branch = (
orders.group_by("branch")
.agg(
orders=pl.len(),
units=pl.col("quantity").sum(),
revenue=pl.col("revenue").sum(),
biggest_order=pl.col("revenue").max(),
)
.sort("revenue", descending=True)
)
print(by_branch)
by_payment = (
orders.group_by("branch", "payment")
.agg(pl.col("revenue").sum())
.sort("branch", "payment")
)
print(by_payment)
PY
uv run summarise.pyKeep the .sort(...). Polars works on groups in parallel and does not promise to return them in any particular order, so without a sort the rows can come back in a different order each run. Pass maintain_order=True to group_by if you want groups in the order they first appear instead.
Check it worked
The branch table has three rows in this order: Lagos with 5 orders, 15 units, revenue 64800 and biggest order 28500; Abuja with 4, 13, 33600 and 14400; Kano with 3, 19, 20500 and 9000. The second table has one row per branch and payment method, eight rows in all.
Step 6 · Join the products and see strict types at work
To total revenue by category you need the product list. join matches rows on a key column. Before joining, see what happens if products.csv is read without the type override, so its codes are numbers while the orders' codes are text. Create join.py:
cd ~/polars-demo
cat > join.py <<'PY'
import polars as pl
from load import load_orders, load_products
orders = load_orders().with_columns(revenue=pl.col("quantity") * pl.col("unit_price"))
try:
orders.join(pl.read_csv("products.csv"), on="product_code")
except pl.exceptions.PolarsError as err:
print("join refused:", type(err).__name__)
products = load_products()
joined = orders.join(products, on="product_code", how="left")
print(joined.select("order_id", "product_code", "product", "category", "revenue"))
print("orders without a product:", joined["product"].null_count())
by_category = (
joined.group_by("category")
.agg(pl.col("revenue").sum())
.sort("revenue", descending=True)
)
print(by_category)
PY
uv run join.pyThe first join fails with an error instead of guessing. pandas would raise here too, but in many other places it converts quietly: an integer column with one missing value becomes floats, and a stray word turns a number column into text. Polars keeps every column to one type and stops when types do not line up. how="left" keeps every order even if its code is missing from the product list; the product columns are then null, which is what null_count() checks.
The same strictness applies when you convert a column yourself. Create strict.py:
cd ~/polars-demo
cat > strict.py <<'PY'
import polars as pl
counts = pl.Series("quantity", ["3", "4", "two"])
try:
counts.cast(pl.Int64)
except pl.exceptions.InvalidOperationError:
print("cast refused: 'two' is not a number")
print(counts.cast(pl.Int64, strict=False))
PY
uv run strict.pycast raises on the first value it cannot convert. With strict=False it turns those values into null instead, which you can then count and investigate. Data typed in by hand, such as a quantity sheet filled in on a phone in several languages, often has values like two or deux; strict casting finds them for you.
Check it worked
join.py prints join refused: SchemaError, then a table with shape: (12, 5) and a product name on every row shown, orders without a product: 0, and a category table: Grains 82700, Cooking 26600, Drinks 9600. strict.py prints cast refused: 'two' is not a number, then a series of three values ending in null.
Step 7 · Rewrite the report as a lazy query
So far every line ran straight away: read_csv read the whole file, then each method made a new frame. That is the eager API. The lazy API builds a plan first. scan_csv reads nothing; it returns a LazyFrame, each method adds to the plan, and collect() runs it. Before running, Polars optimises the plan. It reads only the columns the query uses (projection pushdown) and applies filters while reading (predicate pushdown).
Here is the category report for non-cash payments, written lazily. Create lazy_report.py:
cd ~/polars-demo
cat > lazy_report.py <<'PY'
import polars as pl
orders = pl.scan_csv(
"orders.csv",
schema_overrides={"product_code": pl.String},
try_parse_dates=True,
)
products = pl.scan_csv("products.csv", schema_overrides={"product_code": pl.String})
query = (
orders.with_columns(revenue=pl.col("quantity") * pl.col("unit_price"))
.filter(pl.col("payment") != "cash")
.join(products, on="product_code", how="left")
.group_by("category")
.agg(pl.col("revenue").sum())
.sort("revenue", descending=True)
)
print(type(query).__name__)
print(query.explain())
result = query.collect()
print(result)
result.write_csv("revenue_by_category.csv")
PY
uv run lazy_report.pyThe code reads almost the same as the eager version: you swap read_csv for scan_csv and add collect() at the end. Read the plan from the bottom up, because the scans at the bottom run first. Look at the scan of orders.csv. It reports something like PROJECT 4/7 COLUMNS: order_id, order_date and branch are never used, so Polars does not parse them. The payment != "cash" condition, which you wrote after with_columns, has moved down into the scan as a SELECTION, so cash orders are dropped as the file is read, before any revenue is calculated. The scan of products.csv reads PROJECT 2/3 COLUMNS for the same reason: the report never uses the product name.
On twelve rows this saves nothing you can measure. On a file of several gigabytes, reading only 4 of 7 columns and dropping rows during the scan cuts memory use and run time considerably. For files bigger than memory you also need the streaming engine, covered in the next steps. As a rule of thumb, reach for lazy queries when you read files and eager frames for quick looks.
Check it worked
The script prints LazyFrame, then the plan, then a three-row table: Grains 68300, Drinks 9600, Cooking 5600. These are smaller than in the last step because the three cash orders are gone. ls now shows revenue_by_category.csv.
Step 8 · Hand the result to pandas when a library needs it
Many plotting, statistics and machine learning libraries still expect a pandas DataFrame. to_pandas() converts a Polars frame (it uses pyarrow, which is why you installed it), and pl.from_pandas() converts back. Create to_pandas.py:
cd ~/polars-demo
cat > to_pandas.py <<'PY'
import polars as pl
result = pl.read_csv("revenue_by_category.csv")
frame = result.to_pandas()
print(type(frame).__module__, type(frame).__name__)
print(frame)
print(frame.dtypes)
back = pl.from_pandas(frame)
print("round trip unchanged:", back.equals(result))
PY
uv run to_pandas.pyThe pandas frame gets a fresh 0, 1, 2 index down the left, because pandas always has one. Do the heavy filtering, joining and grouping in Polars, and convert only the small result at the edge of your script.
Check it worked
The first line reads pandas DataFrame. The table shows the three categories with an index 0 to 2, the types are category str and revenue int64, and the last line reads round trip unchanged: True.
When you have finished, remove the demo folder:
cd ~
rm -rf ~/polars-demoNext steps
- Take the lazy API further with Parquet files and the streaming engine in process a file bigger than memory with Polars streaming.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials