Analyze a CSV with Polars: lazy queries and your first grouped total
Learn how Polars DataFrames, LazyFrames, and expressions fit together. Follow a CSV workflow that selects needed columns, filters paid orders, and totals revenue by region, with practical limits for query plans and streaming.
Polars is a library for working with tabular data in Python or Rust. In its lazy API, it builds a plan first instead of running each line immediately; execution begins when you call collect(). This guide follows a small CSV from selecting columns and filtering rows to summing revenue by region. The example data is fictional, and the code is not presented as executed or benchmarked.
The DataFrame Polars works with
Imagine a CSV containing one row per order. Columns such as region, status, and revenue describe each order. A Polars DataFrame groups columns that can have different data types into one table. You can name columns in expressions, filter rows, and combine grouped calculations so the data-processing steps are readable code that can be run again.
Polars uses a DataFrame with the same name as pandas, but that does not mean the libraries behave identically. In particular, Polars does not have pandas-style labeled row indexes. Rows are addressed by their position in the table, while column selection and row filtering are made explicit with select and filter. Before porting .loc, .iloc, or index-alignment logic from pandas, check what key identifies a row in your analysis. Polars centers its API on declaring column computations with expressions. (Polars guide for pandas users: https://docs.pola.rs/user-guide/migration/pandas/)
Immediate and deferred computation
The eager API performs an operation when you call it. It is convenient when you want to open a small table, inspect it, or see intermediate results during exploration. pl.read_csv("orders.csv") reads a file and returns a DataFrame.
The lazy API first builds a sequence of planned operations into a LazyFrame. It has not yet produced the result table. Call collect() at the end to compute the result and return a DataFrame. When starting from a file such as CSV, pl.scan_csv() is a common way to create a LazyFrame. If a DataFrame is already in memory, .lazy() can switch it to a lazy workflow. (Polars Lazy API: https://docs.pola.rs/user-guide/concepts/lazy-api/ ; Using the lazy API: https://docs.pola.rs/user-guide/lazy/using/)
When the operations are considered together, Polars can sometimes move parts of the work earlier. Examples include projection pushdown, which reads only needed columns, and predicate pushdown, which applies a condition as close to the data read as possible. Thus, adding column selection and filters after scan_csv gives the optimizer an opportunity to avoid reading unneeded columns or rows. This is an optimization opportunity, not a promise of a specific speed improvement for every input and operation. query.explain() shows the planned query before execution and can help you inspect the scan, selected columns, and whether conditions have moved toward the reader. The displayed plan can vary by version and query. (Polars optimization guide: https://docs.pola.rs/user-guide/lazy/optimizations/ ; query-plan guide: https://docs.pola.rs/user-guide/concepts/lazy-api/)
Install Polars and make a small CSV
You need Python installed and must know which Python environment you will use. In a terminal, install Polars into that environment and check that it can be imported.
python -m pip install polars
python -c "import polars as pl; print(pl.__version__)"If the second command prints a version, that Python can import polars. If ModuleNotFoundError appears after installation, check whether the terminal that installed the package and the program you are running use different virtual environments or interpreters. The CSV below is fictional order data that you can save and use for practice.
order_id,region,status,revenue,note
1001,East,paid,120,launch
1002,West,paid,90,repeat
1003,East,canceled,40,test
1004,West,paid,130,repeat
1005,East,paid,80,renewalThe table deliberately includes order_id and note, which are not needed in the analysis. The goal is to keep only rows whose status is paid and add revenue by region. In plain language, the task is: read three useful columns, filter by payment status, then calculate each regional total.
Filter and total by region with expressions
The code below starts with scan_csv, builds a transformation plan, executes it, and saves the result. This is a simple local example: put the Python file and orders.csv in the same working folder before running it.
import polars as pl
query = (
pl.scan_csv("orders.csv")
.select("region", "status", "revenue")
.filter(pl.col("status") == "paid")
.group_by("region")
.agg(pl.col("revenue").sum().alias("paid_revenue"))
.sort("region")
)
print(query.explain())
result = query.collect()
print(result)
result.write_csv("paid_revenue_by_region.csv")pl.col("status") is an expression referring to values in a column. Writing the expression alone does not immediately compute the data; it describes an operation inside a Polars context such as .filter(...) or .agg(...). Here, .select(...) narrows the columns, and .filter(...) removes rows that are not paid. Then .group_by("region") collects rows by region, and .agg(...) sums revenue in each group. .alias(...) names the result column, while .sort(...) makes the output region order explicit. Polars expressions are used in contexts such as select, with_columns, filter, and group_by. (Polars getting-started guide, expressions and contexts: https://docs.pola.rs/user-guide/getting-started/)
Adding the paid rows by hand gives East 120+80 = 200 and West 90+130 = 220. The result table should contain two regions and a total column. These are expected values for fictional input, not experimental results from a real file. To verify your own result, recalculate it from the input rows and check that paid_revenue_by_region.csv contains region and paid_revenue.
query.explain() is a way to inspect a plan, not a command that runs the query. Check whether the plan shows a scan of the source CSV, selection of only the three needed columns, and any optimization that moves the payment condition closer to reading. The exact plan text varies with Polars versions and inputs. This is not a benchmark proving that the query is “fast”; it checks whether the plan reflects the intent to reduce unnecessary columns and rows.
When to use collect and how to think about streaming
If you want to do more work on a small result in Python or display it, collect() creates a DataFrame that is easy to use. But if the input is large and the result is also large, materializing the full returned result in memory can be costly. The Lazy API enables planning and optimization; it does not by itself distribute data or remove memory limits.
Polars can run a lazy query with its streaming engine and process some data in batches. For example, you can request this with query.collect(engine="streaming"). However, not every operation runs in streaming mode. Unsupported or inherently non-streaming operations may fall back to the in-memory engine, so do not interpret streaming as a blanket guarantee that any dataset will fit. If you need to send results directly to a file without building the entire result in memory, consider a sink such as LazyFrame.sink_csv(...). For real work, check the current documentation and plan/execution information, then judge suitability using your operations and data size. (Polars streaming guide: https://docs.pola.rs/user-guide/concepts/streaming/ ; sources and sinks: https://docs.pola.rs/user-guide/lazy/sources_sinks/)
Common problems and a safe checking order
The filter keeps unexpected rows: first inspect actual status values and samples for differences such as paid, Paid, or paid with a trailing space. Do not remove case or whitespace by guesswork; find out the source system's rules so the condition matches the intended meaning. An empty result is not a reason to loosen the filter arbitrarily.
A numeric-looking column has an unexpected type: check whether the input includes commas, currency symbols, spaces, or invalid tokens. CSV types may be inferred, so with inconsistent data you can define a schema or schema_overrides, or inspect values as strings before converting them deliberately. Do not enable ignore_errors indiscriminately to hide a read problem; first identify which rows or values violate the expected format. (Polars scan_csv API: https://docs.pola.rs/api/python/stable/reference/api/polars.scan_csv.html)
A pandas script uses an index method that Polars does not have: remember that Polars does not model pandas' labeled row index. Use select for columns and filter for row conditions. Preserve an explicit ID column if the task needs a business identifier. Do not assume that row ordering, type handling, or missing-value meanings are identical across the two libraries; check the documentation for the operation you use. (Polars guide for pandas users: https://docs.pola.rs/user-guide/migration/pandas/)
When Polars fits and when another option may be better
Polars may suit you when you want to express column-oriented table operations as readable expressions and plan file processing deliberately. The Lazy API brings several transformations into one plan and gives the execution engine room to optimize. But “the data is large, so use Polars” is not a reliable rule. Memory use depends not only on the final table but also on intermediate work and the operations involved. If memory is a concern, first narrow the needed columns, inspect the plan and supported streaming paths, and measure resources with a representative workload.
For an initial look at a dataset and immediate inspection of intermediate values, eager read_csv can be simpler. If you already have extensive pandas code and tools, or pandas index and type semantics are central to the workflow, include migration costs in your comparison. Rather than assuming either library is always better, decide based on data size, required operations, existing code, team familiarity, and results you can verify.
References
Polars user guide, Getting started: https://docs.pola.rs/user-guide/getting-started/
Polars user guide, Lazy API: https://docs.pola.rs/user-guide/concepts/lazy-api/
Polars user guide, Using the lazy API: https://docs.pola.rs/user-guide/lazy/using/
Polars user guide, Optimizations: https://docs.pola.rs/user-guide/lazy/optimizations/
Polars user guide, Sources and sinks: https://docs.pola.rs/user-guide/lazy/sources_sinks/
Polars user guide, Streaming: https://docs.pola.rs/user-guide/concepts/streaming/
Polars Python API, `scan_csv`: https://docs.pola.rs/api/python/stable/reference/api/polars.scan_csv.html
Polars user guide, Coming from Pandas: https://docs.pola.rs/user-guide/migration/pandas/