polars.col#
Create an expression representing column(s) in a dataframe.
col
is technically not a function, but it can be used like one.
See the class documentation below for examples and further documentation.
- class polars.functions.col.ColumnFactory(
- name: str | PolarsDataType | Iterable[str] | Iterable[PolarsDataType],
- *more_names: str | PolarsDataType,
Create Polars column expressions.
Notes
An instance of this class is exported under the name
col
. It can be used as though it were a function by calling, for example,pl.col("foo")
. See the__call__()
method for further documentation.This helper class enables an alternative syntax for creating a column expression through attribute lookup. For example
col.foo
creates an expression equal tocol("foo")
. See the__getattr__()
method for further documentation.The function call syntax is considered the idiomatic way of constructing a column expression. The alternative attribute syntax can be useful for quick prototyping as it can save some keystrokes, but has drawbacks in both expressiveness and readability.
Examples
>>> from polars import col >>> df = pl.DataFrame( ... { ... "foo": [1, 2], ... "bar": [3, 4], ... } ... )
Create a new column expression using the standard syntax:
>>> df.with_columns(baz=(col("foo") * col("bar")) / 2) shape: (2, 3) ┌─────┬─────┬─────┐ │ foo ┆ bar ┆ baz │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ f64 │ ╞═════╪═════╪═════╡ │ 1 ┆ 3 ┆ 1.5 │ │ 2 ┆ 4 ┆ 4.0 │ └─────┴─────┴─────┘
Use attribute lookup to create a new column expression:
>>> df.with_columns(baz=(col.foo + col.bar)) shape: (2, 3) ┌─────┬─────┬─────┐ │ foo ┆ bar ┆ baz │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞═════╪═════╪═════╡ │ 1 ┆ 3 ┆ 4 │ │ 2 ┆ 4 ┆ 6 │ └─────┴─────┴─────┘
Methods:
__call__
Call self as a function.
__getattr__
Create a column expression using attribute syntax.
- __call__(
- name: str | PolarsDataType | Iterable[str] | Iterable[PolarsDataType],
- *more_names: str | PolarsDataType,
Call self as a function.
- __getattr__(name: str) Expr [source]
Create a column expression using attribute syntax.
Note that this syntax does not support passing data types or multiple column names.
- Parameters:
- name
The name of the column to represent.
Examples
>>> from polars import col as c >>> df = pl.DataFrame( ... { ... "foo": [1, 2], ... "bar": [3, 4], ... } ... ) >>> df.select(c.foo + c.bar) shape: (2, 1) ┌─────┐ │ foo │ │ --- │ │ i64 │ ╞═════╡ │ 4 │ │ 6 │ └─────┘