Skip to content

polars.DataFrame.to_expr

Converts a polars DataFrame to a Pyoframe Expression by using the last column for values and the previous columns as dimensions.

See Special Functions for more details.

Examples:

>>> import polars as pl
>>> df = pl.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6], "z": [7, 8, 9]})
>>> df.to_expr()
<Expression height=3 terms=3 type=constant>
┌─────┬─────┬────────────┐
│ x   ┆ y   ┆ expression │
│ (3) ┆ (3) ┆            │
╞═════╪═════╪════════════╡
│ 1   ┆ 4   ┆ 7          │
│ 2   ┆ 5   ┆ 8          │
│ 3   ┆ 6   ┆ 9          │
└─────┴─────┴────────────┘
Source code in pyoframe/_monkey_patch.py
def polars_df_to_expr(self: pl.DataFrame) -> Expression:
    """Converts a [polars](https://pola.rs/) `DataFrame` to a Pyoframe [Expression][pyoframe.Expression] by using the last column for values and the previous columns as dimensions.

    See [Special Functions](../../learn/concepts/special-functions.md#dataframeto_expr) for more details.

    Examples:
        >>> import polars as pl
        >>> df = pl.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6], "z": [7, 8, 9]})
        >>> df.to_expr()
        <Expression height=3 terms=3 type=constant>
        ┌─────┬─────┬────────────┐
        │ x   ┆ y   ┆ expression │
        │ (3) ┆ (3) ┆            │
        ╞═════╪═════╪════════════╡
        │ 1   ┆ 4   ┆ 7          │
        │ 2   ┆ 5   ┆ 8          │
        │ 3   ┆ 6   ┆ 9          │
        └─────┴─────┴────────────┘
    """
    name = self.columns[-1]
    return Expression(
        self.rename({name: COEF_KEY})
        .drop_nulls(COEF_KEY)
        .with_columns(pl.lit(CONST_TERM).alias(VAR_KEY)),
        name=name,
    )