Add an index column
Create sequential row labels during a DataFrame select.
Polars · Function
Generates an integer range with an inclusive start and exclusive end. It returns an expression by default or an immediately evaluated Series when eager=True.
int_range builds integer values from an inclusive start toward an exclusive end using the requested step. By default it returns a lazy expression; setting eager=True evaluates it immediately as a Series, and omitting end treats the supplied start as the exclusive endpoint from zero.
polars.int_range(start: int | IntoExprColumn = 0, end: int | IntoExprColumn | None = None, step: int = 1, *, dtype: PolarsIntegerType | DataTypeExpr = Int64, eager: bool = False) → Expr | Series| Name | Type | Description |
|---|---|---|
start | int | IntoExprColumn | Start of the range, inclusive; defaults to 0. |
end | int | IntoExprColumn | None | Exclusive endpoint. If omitted, start is used as the endpoint and the actual start becomes 0. |
step | int | Step size of the range. |
dtype | PolarsIntegerType | DataTypeExpr | Integer data type for the output. |
eager | bool | If true, evaluate immediately and return a Series; otherwise return an expression. |
Expr or SeriesColumn of integer data type dtype.
step controls the increment between generated values.dtype argument selects the integer type of the output.int_ranges instead.end is omitted, the single positional value becomes the exclusive endpoint and the range starts at zero.eager=True when immediate materialization is required.import polars as pl
df = pl.DataFrame({"value": [10, 20, 30]})
result = df.select(
pl.int_range(pl.len(), dtype=pl.UInt32).alias("index"),
pl.all(),
)
print(result)Creates a zero-based UInt32 index expression whose length matches the input DataFrame.
Create sequential row labels during a DataFrame select.
Produce a materialized sequence for direct Series use.
Generate values with a custom increment or integer dtype.
pl.int_range generate, and what are its endpoint and dtype defaults?It generates an integer range with an inclusive start and exclusive end. The default step is 1, and the default dtype is Int64.
Follow-up: How would you create a DataFrame index? Use pl.int_range(pl.len(), dtype=pl.UInt32) in a select expression and give it an alias.
eager argument change the return type?With eager=False, the function returns an expression that can participate in a DataFrame query. With eager=True, it evaluates immediately and returns a Series.
Follow-up: Why might the expression form be preferable? It can be composed with select and other expressions before execution.
end do?The one-argument form uses the supplied value as end, sets start to zero, and therefore produces values from zero up to but not including that value. For example, pl.int_range(3, eager=True) yields 0, 1, and 2.
Follow-up: How can the output type be narrowed for an index? Pass an integer dtype such as pl.UInt32 through dtype.
int_ranges