如何在极性中使用when, then和else的多个条件?

  • 本文关键字:else then 条件 when python-polars
  • 更新时间 :
  • 英文 :


我有一个三列的数据集。列A要检查字符串。如果字符串匹配foospam,则应将另外两列LG的同一行中的值更改为XX。为此,我尝试了以下方法:

df = pl.DataFrame(
{
"A": ["foo", "ham", "spam", "egg",],
"L": ["A54", "A12", "B84", "C12"],
"G": ["X34", "C84", "G96", "L6",],
}
)
print(df)
shape: (4, 3)
┌──────┬─────┬─────┐
│ A    ┆ L   ┆ G   │
│ ---  ┆ --- ┆ --- │
│ str  ┆ str ┆ str │
╞══════╪═════╪═════╡
│ foo  ┆ A54 ┆ X34 │
│ ham  ┆ A12 ┆ C84 │
│ spam ┆ B84 ┆ G96 │
│ egg  ┆ C12 ┆ L6  │
└──────┴─────┴─────┘

预期结果

shape: (4, 3)
┌──────┬─────┬─────┐
│ A    ┆ L   ┆ G   │
│ ---  ┆ --- ┆ --- │
│ str  ┆ str ┆ str │
╞══════╪═════╪═════╡
│ foo  ┆ XX  ┆ XX  │
│ ham  ┆ A12 ┆ C84 │
│ spam ┆ XX  ┆ XX  │
│ egg  ┆ C12 ┆ L6  │
└──────┴─────┴─────┘

I tried this

df = df.with_column(
pl.when((pl.col("A") == "foo") | (pl.col("A") == "spam"))
.then((pl.col("L")= "XX") & (pl.col( "G")= "XX"))
.otherwise((pl.col("L"))&(pl.col( "G")))
)

然而,这不起作用。有人能帮我一下吗?

为多个列设置相同的值,可以使用:

df.with_columns(
pl.when(pl.col("A").is_in(["foo", "spam"]))
.then(pl.lit("XX"))
.otherwise(pl.col("L", "G"))
.keep_name()
)
shape: (4, 3)
┌──────┬─────┬─────┐
│ A    ┆ L   ┆ G   │
│ ---  ┆ --- ┆ --- │
│ str  ┆ str ┆ str │
╞══════╪═════╪═════╡
│ foo  ┆ XX  ┆ XX  │
│ ham  ┆ A12 ┆ C84 │
│ spam ┆ XX  ┆ XX  │
│ egg  ┆ C12 ┆ L6  │
└──────┴─────┴─────┘

.is_in()可以代替多个== x | == y链。

要一次用不同的值更新多个列,您可以使用.map()和字典:

df.with_columns(
pl.when(pl.col("A").is_in(["foo", "spam"]))
.then(pl.col("L", "G").map(
lambda col: {
"L": "XX",
"G": "YY",
}.get(col.name)))
.otherwise(pl.col("L", "G"))
)
shape: (4, 3)
┌──────┬─────┬─────┐
│ A    ┆ L   ┆ G   │
│ ---  ┆ --- ┆ --- │
│ str  ┆ str ┆ str │
╞══════╪═════╪═════╡
│ foo  ┆ XX  ┆ YY  │
│ ham  ┆ A12 ┆ C84 │
│ spam ┆ XX  ┆ YY  │
│ egg  ┆ C12 ┆ L6  │
└──────┴─────┴─────┘

当使用.map时,整个列被传递(作为pl.Series),这意味着如果需要,您也可以操作它:

df.with_columns(
pl.when(pl.col("A").is_in(["foo", "spam"]))
.then(pl.col("L", "G").map(
lambda col: {
"L": col.str.to_lowercase(),
"G": "prefix_" + col
}.get(col.name)))
.otherwise(pl.col("L", "G"))
)
shape: (4, 3)
┌──────┬─────┬────────────┐
│ A    ┆ L   ┆ G          │
│ ---  ┆ --- ┆ ---        │
│ str  ┆ str ┆ str        │
╞══════╪═════╪════════════╡
│ foo  ┆ a54 ┆ prefix_X34 │
│ ham  ┆ A12 ┆ C84        │
│ spam ┆ b84 ┆ prefix_G96 │
│ egg  ┆ C12 ┆ L6         │
└──────┴─────┴────────────┘

最新更新