sqlstringexpressionpython-polars

Possible to Stringize a Polars Expression?


Is it possible to stringize a Polars expression and vice-versa?

For example, convert df.filter(pl.col('a')<10) to a string of "df.filter(pl.col('a')<10)".

Is roundtripping possible e.g. eval("df.filter(pl.col('a')<10)") for user input or tool automation?

I know this can be done with a SQL expression but I'm interested in native. I want to show the specified filter in the title of plots.


Solution

  • Expressions

    >>> expr = pl.col("foo") > 2
    >>> print(str(expr))
    [(col("foo")) > (2i32)]
    

    LazyFrames

    >>> import io
    >>> df = pl.DataFrame({
    ...     "foo": [1, 2, 3]
    ... })
    >>> json_state = df.lazy().filter(expr).serialize(format="json")
    >>> query_plan = pl.LazyFrame.deserialize(io.StringIO(json_state), format="json")
    >>> query_plan.collect()
    shape: (1, 1)
    ┌─────┐
    │ foo │
    │ --- │
    │ i64 │
    ╞═════╡
    │ 3   │
    └─────┘