将包含单个元素数组的列转换为具有 Python 极坐标的浮点数列

Convert column containing single element arrays into column of floats with Python polars

我最近开始使用 polars (https://pola-rs.github.io/polars/py-polars/html/reference/index.html)

我的数据框中有一列包含单个元素数组(keras 的输出 model.predict):

X
object
[0.49981183]
[0.49974033]
[0.4997973]
[0.49973667]
[0.49978396]

我想把它转换成一列浮点数:

0.49981183
0.49974033
0.4997973
0.49973667
0.49978396

我试过:

data = data.with_column((pl.col("X")[0]).alias("Y"))

但它给了我这个错误:

TypeError: 'Expr' object is not subscriptable

正确的做法是什么?大约有 6700 万行,所以越快越好

干杯

不幸的是,Object 类型的列通常是 dead-end。来自 Polars 用户指南的 Data Types 部分:

Object: A limited supported data type that can be any value.

由于支持有限,对 Object 类型的列的操作经常抛出异常。

但是,可能 有一种方法可以在这种特定情况下检索值。例如,让我们特意创建一个 object.

类型的列
import polars as pl
data_as_list = [[0.49981183], [0.49974033],
                [0.4997973], [0.49973667], [0.49978396]]

df = pl.DataFrame([
        pl.Series("X", values=data_as_list, dtype=pl.Object),
])
print(df)
shape: (5, 1)
┌──────────────┐
│ X            │
│ ---          │
│ object       │
╞══════════════╡
│ [0.49981183] │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ [0.49974033] │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ [0.4997973]  │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ [0.49973667] │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ [0.49978396] │
└──────────────┘

这种方法可能行得通...

def attempt_recover(series: pl.Series) -> pl.Series:
    return pl.Series(values=[val[0] for val in series])

df.with_column(pl.col("X").map(attempt_recover).alias("X_recovered"))
shape: (5, 2)
┌──────────────┬─────────────┐
│ X            ┆ X_recovered │
│ ---          ┆ ---         │
│ object       ┆ f64         │
╞══════════════╪═════════════╡
│ [0.49981183] ┆ 0.499812    │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ [0.49974033] ┆ 0.4997      │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ [0.4997973]  ┆ 0.4997973   │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ [0.49973667] ┆ 0.499737    │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ [0.49978396] ┆ 0.499784    │
└──────────────┴─────────────┘

首先在一小部分数据上尝试这个。 这可能行不通。(而且不会很快。)

您要做的是改变将来自 Keras 的模型预测结果加载到 Polars 中的方式,以防止获得 Object 类型的列。 (通常这意味着在加载到 Polars 之前索引一个 array/list 输出以从 array/list 中提取数字。)