6

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'
drhagen
  • 8,331
  • 8
  • 53
  • 82

1 Answers1

12

Like so:

val = pl.select(expr).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(expr)[0, 0] as an alternative.

Nick ODell
  • 15,465
  • 3
  • 32
  • 66