Polars - 转换为 pl.List 后无法计算熵

问题描述 投票:0回答:1

我正在尝试计算列表的熵,但我需要先进行转换:

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()

但这给出了:

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

这里出了什么问题?

python python-polars
1个回答
0
投票

对于这个问题,您需要做几件事:

  1. 正确解析数字(包括逗号后面的空格)
  2. 使用
    .list.eval(…entropy())
    计算每个列表的熵
  3. 结果返回一个长度为1的列表,所以我们获取计算出的熵
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 │
    # └──────────┘
)
© www.soinside.com 2019 - 2024. All rights reserved.