Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Polars – can't compute entropy after conversion to pl.List

I’m trying to compute the entropy of a list, but I need to do a conversion first :

import polars as pl
df = pl.DataFrame({"Result": "1, 2, 3"})

df.select(pl.col("Result").str.split(",").cast(pl.List(pl.Float64)).entropy()).collect()

but this gives :

ComputeError: cannot cast List type (inner: 'Float64', to: 'Float64')

What’s wrong here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For this problem you’ll need to do a couple of things:

  1. properly parse the numbers (including the space after the comma)
  2. use .list.eval(…entropy()) to calculate the entropy per list
  3. the result returns a list of length 1, so we grab the calculated entropy
import polars as pl
print(pl.__version__) # 0.20.2

df = pl.DataFrame({"Result": ["1, 2, 3", "4, 5, 6"]})

print(
    df.select(
        pl.col("Result").str.split(", ")   # ①
        .cast(pl.List(pl.Float64))
        .list.eval(pl.element().entropy()) # ②
        .list.get(0)                       # ③
    )
    # shape: (2, 1)
    # ┌──────────┐
    # │ Result   │
    # │ ---      │
    # │ f64      │
    # ╞══════════╡
    # │ 1.011404 │
    # │ 1.085189 │
    # └──────────┘
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading