3

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.

  • There is the [SQL context](https://pola-rs.github.io/polars/py-polars/html/reference/expressions/api/polars.sql_expr.html#polars.sql_expr) but you'd need to alter the assignment part e.g. `df.with_columns(pl.sql_expr("col1 + col2 as col3"))` – jqurious Jul 25 '23 at 12:17

1 Answers1

2

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:

ctxt = pl.SQLContext(
    frames = {"df": df}
)
ctxt.execute("""
    SELECT col2 + col1 as col3 FROM df
    """,
    eager=True
)

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.

ritchie46
  • 10,405
  • 1
  • 24
  • 43
  • I have an expression like '( ind128715 * ind128717/12 ) / ( 1 - (1+ ind128717/12) ** - dim23358___prop37803 )' but sql_expr giving an error 'Expected an expression : found *' – Murtaza Arif Aug 21 '23 at 03:28