如何将 LabelEncoder 应用于 Polars DataFrame 列?

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

我正在尝试将 scikit-learn 的

LabelEncoder
与 Polars DataFrame 一起使用来对分类列进行编码。这是我的代码:

from sklearn.preprocessing import LabelEncoder

le = LabelEncoder()

SO = pl.DataFrame(
    {"Color" : ["red","white","blue"]}
)

(
    SO
    .with_columns(
       le.fit_transform(pl.col("Color")) 
    )
)

但是,我收到以下错误:

ValueError: y should be a 1d array, got an array of shape () instead.

我还尝试将列转换为 NumPy 数组:

(
    SO
    .with_columns(
       le.fit_transform(pl.col("Color").to_numpy()) 
    )
)

但这会导致另一个错误:

AttributeError: 'Expr' object has no attribute 'to_numpy'

我发现我可以使用

cast(pl.Categorical).to_physical()
,但我想在我的测试数据集上使用类似
transform()
的东西。

(
    SO
    .with_columns(
       pl.col("Color").cast(pl.Categorical).to_physical().alias("Color_encoded"),
    )
)
scikit-learn python-polars
1个回答
0
投票

对于采用整个值序列的外部 API 的调用,可以使用

enc.fit_transform
pl.Expr.map_batches

import polars as pl

from sklearn.preprocessing import LabelEncoder

df = pl.DataFrame({
    "Color" : ["red","white","blue"]
})

enc = LabelEncoder()

df.with_columns(
    pl.col("Color").map_batches(lambda x: enc.fit_transform(x))
)
shape: (3, 1)
┌───────┐
│ Color │
│ ---   │
│ i64   │
╞═══════╡
│ 1     │
│ 2     │
│ 0     │
└───────┘
© www.soinside.com 2019 - 2024. All rights reserved.