If I have a Polars literal, how can I extract the value?
import polars as pl
expr = pl.lit(0.5)
val = float(expr)
# TypeError: float() argument must be a string or a real number, not 'Expr'
Like so:
literal = pl.lit(0.5)
val = pl.select(literal).item()
Explanation: a Polars literal is an Expr object. An Expr object can be evaluated using pl.select()
. That returns a DataFrame. To get the scalar value from the DataFrame, you can use DataFrame.item()
.
Note: .item()
was added in release 0.15.9 of polars. If you are using a version prior to this, you can use pl.select(literal)[0, 0]
as an alternative.