Add readable row identifiers
Assigning stable row labels before exporting or displaying tabular data.
Polars · Module
Adds a sequential integer column as the first column of a DataFrame. The column name and starting offset are configurable.
Call this DataFrame method to return a copy with a sequential integer column inserted at the front. You can choose the column name and starting value; the resulting column is ordinary data rather than a special index.
DataFrame.with_row_index(name: str = 'index', offset: int = 0) → DataFrame| Name | Type | Description |
|---|---|---|
name | str = 'index' | Name of the index column. |
offset | int = 0 | Start the index at this offset. Cannot be negative. |
A DataFrame containing the new row-index column as its first column.
import polars as pl
df = pl.DataFrame({"value": [10, 20, 30]})
result = df.with_row_index("id", offset=100)
print(result)Creates a new first column named id containing 100, 101, and 102.
Assigning stable row labels before exporting or displaying tabular data.
Starting numbering at a domain-specific base such as 1 or 1000.
Building an index column through expressions when working in expression-oriented transformations.
It returns a DataFrame with a row-index column inserted as the first column. By default, that column is named index and starts at zero.
Follow-up: How would you start the sequence elsewhere? Pass a nonnegative offset, such as offset=100.
The name parameter controls the index column's name, while offset controls its starting value. For example, with_row_index("id", offset=100) produces an id column beginning at 100.
Follow-up: What happens if the offset is negative? The call is invalid because negative offsets are not permitted.
The generated column uses UInt32 in the normal configuration, or UInt64 when the 64-bit index configuration is enabled. It is still a regular column without special index behavior.
Follow-up: What alternative does the documentation mention for constructing an index expression? Use int_range() together with len().
polars.DataFrame.with_row_countpolars.row_indexpolars.int_rangepolars.len