Polars:如果另一列满足条件,则更改数据框中的值

use*_*022 8 python python-polars

我有这个数据框

一 二
A 你好
乙 世界

我想把hola改为hello:

一 二
A 你好
乙 世界

如何根据另一列中的条件更改行的值?

例如,使用 PostgreSQL 我可以这样做:

UPDATE my_table SET two = 'hello' WHERE one = 'a';
Run Code Online (Sandbox Code Playgroud)

或者在 Spark 中

my_table.withColumn("two", when(col("one") == "a", "hello"))
Run Code Online (Sandbox Code Playgroud)

我尝试过使用with_columns(pl.when(pl.col("one") == "a").then("hello")),但这改变了“一”列。

编辑:我可以创建一个 SQL 实例并通过 SQL 绘制我的方式,但必须有方法通过 Python API 来实现这一点。

Dea*_*gor 11

您非常接近,with_columns(pl.when(pl.col("one") == "a").then("hello"))但您需要告诉它应该是哪一列。

当您不告诉它您所指的列时,它必须猜测,在这种情况下,它猜测您所指的列。

相反,你会这样做

(df 
    .with_columns(
        two=pl.when(pl.col('one')=='a')
                .then(pl.lit('hello'))
                .otherwise(pl.col('two')))
)
Run Code Online (Sandbox Code Playgroud)

这使用 **kwargs 输入with_columns来允许指定的列位于等号左侧,就好像它是函数的参数一样。您还可以使用像这样的别名语法...

(df 
    .with_columns(
        (pl.when(pl.col('one')=='a')
                .then(pl.lit('hello'))
                .otherwise(pl.col('two')))
            .alias('two')
                )
)
Run Code Online (Sandbox Code Playgroud)

请注意,我将整个“when/then/otherwise”括在括号中。when/then/otherwise 和 alias 的操作顺序很奇怪,所以我发现最好总是将它们完全括在括号中,以避免意外结果。最坏的情况是你有多余的括号,这不会伤害任何东西。