Select the leading column
Use pl.first() in select expressions when the first column of the current context is needed.
Polars · Function
Returns an expression that selects the first column when no names are supplied, or the first value from each named column when names are supplied.
pl.first returns an expression whose behavior depends on whether column names are supplied. Without names it selects the first column in the current context; with one or more names it selects the first value from each named column.
polars.first(*columns: str) → Expr| Name | Type | Description |
|---|---|---|
columns | str | One or more column names. |
Expr
import polars as pl
df = pl.DataFrame({"a": [1, 8, 3], "b": [4, 5, 2]})
print(df.select(pl.first()))
print(df.select(pl.first("b")))The first selection returns column a, while the named selection returns the first value from column b.
Use pl.first() in select expressions when the first column of the current context is needed.
Use pl.first("name", "score") to retrieve the initial row's values from selected columns.
Use several column names when building a compact one-row selection from a DataFrame.
With no arguments, pl.first() returns an expression that takes the first column of the context. For example, selecting it from a DataFrame returns the complete first column.
Follow-up: What happens with multiple names? pl.first("a", "c") returns one first value for each named column, producing a one-row result.
Passing column names changes the operation from column selection to value extraction. pl.first("b") selects the first value of column b.
Follow-up: How can the result be verified? Inspect the selected DataFrame: the named form has one row, whereas the no-argument form has the input height.
The function accepts one or more column names and returns an Expr. Multiple names are handled together, so each named column contributes its first value to the result.
Follow-up: What should be checked when using several names? Confirm that every supplied name exists and that the resulting columns correspond to those names.
polars.lastpolars.Expr.first