Dynamic final-column selection
Selecting the rightmost column without hard-coding its name.
Polars · Function
pl.last returns the last column when called without names, or the last value from each named column when names are supplied.
pl.last produces an expression whose behavior depends on whether column names are supplied: without names it selects the final column in the current context; with names it selects the final value from each named column.
polars.last(*columns: str) → Expr| Name | Type | Description |
|---|---|---|
columns | str | One or more column names. |
Expr
pl.last to retrieve either the final column or terminal values, depending on whether names are passed.pl.last() and calling pl.last with one or more names are different operations: the former returns a whole column, while the latter returns terminal values.import polars as pl
df = pl.DataFrame({
"a": [1, 8, 3],
"b": [4, 5, 2],
"c": ["foo", "bar", "baz"],
})
print(df.select(pl.last()))
print(df.select(pl.last("a")))
print(df.select(pl.last("b", "c")))The first selection returns the final column, while the other selections return the final value from each named column.
Selecting the rightmost column without hard-coding its name.
Extracting terminal values from one or more known columns.
Selecting several columns’ final values in one expression.
pl.last change behavior when column names are provided?With no arguments, pl.last() returns an expression that takes the last column of the current context. With one or more column names, it takes the last value from each named column.
Follow-up: What does pl.last("b", "c") produce? It returns a one-row result containing the final value of both selected columns.
columns parameter represent?The columns parameter accepts one or more column names. Supplying several names lets the expression retrieve the terminal value for each of those columns in one selection.
Follow-up: How would you select the final value from a dynamically chosen set of columns? Build the names programmatically and expand them as positional arguments when calling pl.last.
pl.last() is useful when the selection context itself determines which column is last. For example, selecting it from a DataFrame with columns a, b, and c returns column c with all its rows.
Follow-up: How does this differ from pl.col("c").last()? The latter explicitly targets column c and returns its final value, rather than selecting the final column wholesale.
polars.Expr.lastpolars.colpolars.first