19

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'

1 Answer 1

32

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.

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.