pythondataframepython-polars

Pandas.eval replacement in polars


Suppose I have an expression like "col3 = col2 + col1" so pandas we can directly call pandas.dataframe.eval() but in polars I cannot find such method.

I have series.eval in polars but no luck as I want evaluate user given expression on a dataframe.


Solution

  • Acception strings

    You can pass SQL to pl.sql_expr.

    df = pl.DataFrame({
        "col1": [1, 2],
        "col2": [1, 2],
    })
    df.select(
        pl.sql_expr("col2 + col1 as col3")
    )
    

    Or you can run a complete SQL query with pl.sql

    pl.sql("SELECT col2 + col1 as col3 FROM df").collect()
    
    shape: (2, 1)
    ┌──────┐
    │ col3 │
    │ ---  │
    │ i64  │
    ╞══════╡
    │ 2    │
    │ 4    │
    └──────┘
    

    Accept expressions directly

    i want evaluate user given expression on a dataframe.

    I would accept pl.Expression directly instead of strings. This gives more type safety than strings and probably also a better user experience as you can have autocomplete and the IDE may show available methods/arguments.