Pandas 替换 Python 极地中的等价物

Pandas REPLACE equivalent in Python Polars

有没有一种优雅的方法来重新编码 polars 数据帧中的值。

例如

1->0, 
2->0, 
3->1... 

在Pandas中很简单:

df.replace([1,2,3,4,97,98,99],[0,0,1,1,2,2,2])

在 polars 中,您可以构建称为 if -> then -> otherwise 的柱状 if else statetements 表达式。

假设我们有这个 DataFrame

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

我们想用以下值替换它们:

from_ = [1, 2]
to_ = [99, 12]

我们可以这样写:

df.with_column(
    pl.when(pl.col("a") == from_[0])
    .then(to_[0])
    .when(pl.col("a") == from_[1])
    .then(to_[1])
    .otherwise(pl.col("a")).alias("a")
)
shape: (5, 1)
┌─────┐
│ a   │
│ --- │
│ i64 │
╞═════╡
│ 99  │
├╌╌╌╌╌┤
│ 12  │
├╌╌╌╌╌┤
│ 3   │
├╌╌╌╌╌┤
│ 4   │
├╌╌╌╌╌┤
│ 5   │
└─────┘

不要重复自己

现在,写得非常快变得非常乏味,所以我们可以编写一个函数来生成这些表达式以供使用,我们是程序员不是吗!

因此,要替换为您建议的值,您可以这样做:

from_ = [1,2,3,4,97,98,99]
to_ = [0,0,1,1,2,2,2]


def replace(column, from_, to_):
    # initiate the expression with `pl.when`
    branch =  pl.when(pl.col(column) == from_[0]).then(to_[0])

    
    # for every value add a `when.then`
    for (from_value, to_value) in zip(from_, to_):
        branch = branch.when(pl.col(column) == from_value).then(to_value)

    # finish with an `otherwise`
    return branch.otherwise(pl.col(column)).alias(column)
    


df.with_column(replace("a", from_, to_))

输出:

shape: (5, 1)
┌─────┐
│ a   │
│ --- │
│ i64 │
╞═════╡
│ 0   │
├╌╌╌╌╌┤
│ 0   │
├╌╌╌╌╌┤
│ 1   │
├╌╌╌╌╌┤
│ 1   │
├╌╌╌╌╌┤
│ 5   │
└─────┘