Sub topic 3
Creating a LazyFrame with lazy() and LazyFrame()
This chapter assumes you know basic Python and the Polars expression API (pl.col, select, filter, with_columns). You should also know how to build a DataFrame. Here you learn the two ways to create a LazyFrame from data that is already in memory.
What a LazyFrame is
A LazyFrame is an object that stores a query plan instead of data. Each method you call on it adds a step to the plan. Nothing is computed until you ask for a result. The next chapter covers running the plan.
Two ways to create one
You can create a LazyFrame in two ways:
- Call
.lazy()on an existingDataFrame. - Call
pl.LazyFrame(...)with the same arguments you would givepl.DataFrame(...).
import polars as pl
df = pl.DataFrame({
"city": ["Oslo", "Lima", "Oslo", "Cairo"],
"temp": [3.0, 19.5, 5.0, 28.0],
})
# Way 1: convert an existing DataFrame.
lf1 = df.lazy()
# Way 2: build a LazyFrame directly.
lf2 = pl.LazyFrame({
"city": ["Oslo", "Lima", "Oslo", "Cairo"],
"temp": [3.0, 19.5, 5.0, 28.0],
})
print(type(lf1))
print(lf1.collect_schema())
print(lf2.collect_schema())Both objects hold the same data and have the same schema. Use .lazy() when you already have a DataFrame. Use pl.LazyFrame(...) when you are starting from a dictionary, a list of rows, or another in-memory source and do not need a DataFrame first.
Building a query
Once you have a LazyFrame, you write the same expressions you use eagerly. The difference is that each call returns a new LazyFrame and runs nothing.
import polars as pl
lf = pl.LazyFrame({
"city": ["Oslo", "Lima", "Oslo", "Cairo"],
"temp": [3.0, 19.5, 5.0, 28.0],
})
query = (
lf.filter(pl.col("temp") > 4)
.with_columns(temp_f=pl.col("temp") * 9 / 5 + 32)
.select("city", "temp_f")
)
print(type(query))
print(query.collect())The first print shows that query is still a LazyFrame. Only collect() produces a DataFrame.
Common errors
- Treating a LazyFrame like a DataFrame. A
LazyFramehas no rows to show. Callingprint(lf)prints the plan summary, not the data. Methods such as.height,.shape, and.to_pandas()are not available. Call.collect()first. - Forgetting to assign the result. Methods return a new
LazyFrame. Callinglf.filter(...)without assigning the result changes nothing. - Calling
.lazy()too late. Converting after an expensive eager step gives the optimiser nothing to work with for that step. Convert as early as you can.
Exercise
You have a DataFrame df with columns a and b. Write the code to get a LazyFrame that keeps rows where a > 10 and selects only column b. Does the code run the filter?
Show answer
q = df.lazy().filter(pl.col("a") > 10).select("b"). It does not run the filter. q is a LazyFrame that holds the plan. The filter runs only when you call q.collect().