Sub topic 2
Creating and Modifying Columns
Assume you know pandas DataFrames, method chaining, and basic Python. Polars uses expressions instead of row-aligned Series operations. DataFrames are immutable, so methods return new frames rather than changing the original.
Creating and Modifying Columns
Use with_columns to add or replace columns. Use pl.col("name") to refer to a column.
import polars as pl
orders = pl.DataFrame({
"region": ["West", "West", "East"],
"price": [40.0, 75.0, 60.0],
"qty": [3, 2, 1],
})
orders = orders.with_columns(
(pl.col("price") * pl.col("qty")).alias("total"),
pl.when(pl.col("qty") > 1)
.then(pl.lit("multiple"))
.otherwise(pl.lit("single"))
.alias("order_type"),
)
print(orders)with_columns can create several columns in one operation. It can also replace an existing column when the new expression has the same name.
Null Versus NaN
Polars treats null and floating-point NaN differently:
nullmeans a missing value.NaNis a special floating-point value.is_null()andfill_null()handle onlynull.is_nan()detects onlyNaN.
values = pl.DataFrame({"x": [1.0, None, float("nan")]})
print(values.select(
pl.col("x").is_null().alias("missing"),
pl.col("x").is_nan().alias("not_a_number"),
pl.col("x").fill_null(0.0).alias("filled"),
))Use fill_nan separately when NaN should become a regular value.
Grouping and Aggregation
Use group_by followed by agg. Aggregations produce one row per group.
summary = (
orders.group_by("region")
.agg(
pl.col("total").sum().alias("revenue"),
pl.len().alias("orders"),
)
.sort("revenue", descending=True)
)
print(summary)Replacing `transform` with `over`
A window expression computes a group value while keeping every original row. This replaces many uses of pandas groupby().transform().
orders = orders.with_columns(
pl.col("total").mean().over("region").alias("region_mean")
)Joins and Concatenation
Use join to combine columns from related frames. Use pl.concat to append rows from frames with compatible schemas.
targets = pl.DataFrame({
"region": ["West", "East"],
"target": [200.0, 100.0],
})
joined = orders.join(targets, on="region", how="left")
combined = pl.concat([orders, orders])Exercise
Which Polars method keeps every input row while calculating a value per group?
Show answer
Use a window expression with over, such as pl.col("total").mean().over("region").