Name derived columns
A calculation or string transformation would otherwise inherit an unsuitable column name.
Polars · Module
Renames the output of a Polars expression. Use it to give derived or literal expressions explicit, non-conflicting column names.
Call alias on an expression to assign the name of the column it produces. This is useful when a transformation would otherwise inherit an undesired root name, and it also lets literal expressions receive distinct names so multiple generated columns do not collide.
Expr.alias(name: str) → Expr| Name | Type | Description |
|---|---|---|
name | str | The new name. |
Expr
alias changes the name assigned to an expression's output.name argument supplies the output label.alias at the end of the expression.name.map, name.prefix, and name.suffix.import polars as pl
df = pl.DataFrame({"a": [1, 2, 3], "b": ["x", "y", "z"]})
result = df.with_columns(
(pl.col("a") + 10).alias("a_plus_10"),
pl.col("b").str.to_uppercase().alias("c"),
)
print(result)Creates two derived columns and explicitly assigns their output names.
A calculation or string transformation would otherwise inherit an unsuitable column name.
Several literal expressions are added in one projection and need distinct output labels.
A computed expression must be prevented from overwriting an existing column.
Expr.alias do?Expr.alias returns an expression whose output name is the supplied string. In a projection such as with_columns, that name becomes the resulting column name.
Follow-up: How would you name a transformed column without using a fixed string? Use the related expression naming methods such as name.map, name.prefix, or name.suffix.
with_columns?Use alias after the transformation expression, for example pl.col("b").str.to_uppercase().alias("c"). The transformation is evaluated first, and the resulting expression is labeled c.
Follow-up: What problem can arise with pl.lit expressions? Multiple literals may otherwise share a default name, so give each one a unique alias.
Expr.alias?The method accepts one name argument, which is the new output name, and returns an Expr. It is appropriate when the desired output label is known directly.
Follow-up: When the name must be computed from the input root name, which documented alternatives should you investigate? name.map, name.prefix, and name.suffix.
Expr.name.mapExpr.name.prefixExpr.name.suffix