2

how to assign same value to multiple columns based on another column condition in python polars

df = pl.DataFrame({
   "A": ["a", "b", "a", "c"], 
   "B": [23,45,60,50], 
   "C": [11, 26, 63, 84]
})

┌─────┬─────┬─────┐
│ A   ┆ B   ┆ C   │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ a   ┆ 23  ┆ 11  │
│ b   ┆ 45  ┆ 26  │
│ a   ┆ 60  ┆ 63  │
│ c   ┆ 50  ┆ 84  │
└─────┴─────┴─────┘


based on column A if value is "a" , then value for column B and C need to be set as 0

need output as

┌─────┬─────┬─────┐
│ A   ┆ B   ┆ C   │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ a   ┆ 0   ┆ 0   │
│ b   ┆ 45  ┆ 26  │
│ a   ┆ 0   ┆ 0   │
│ c   ┆ 50  ┆ 84  │
└─────┴─────┴─────┘
  • Does this answer your question? [How to swap column values on conditions in python polars?](https://stackoverflow.com/questions/73717556/how-to-swap-column-values-on-conditions-in-python-polars) – Marcelo Paco Apr 04 '23 at 04:01

1 Answers1

2

How can I use when, then and otherwise with multiple conditions in polars?

df.with_columns(
   pl.when(pl.col("A") != "a")
     .then(pl.col("B", "C"))
     .otherwise(0)
)
shape: (4, 3)
┌─────┬─────┬─────┐
│ A   ┆ B   ┆ C   │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ a   ┆ 0   ┆ 0   │
│ b   ┆ 45  ┆ 26  │
│ a   ┆ 0   ┆ 0   │
│ c   ┆ 50  ┆ 84  │
└─────┴─────┴─────┘

For this example you could also use .then(pl.exclude("A")) instead of having to name the remaining columns.

jqurious
  • 9,953
  • 1
  • 4
  • 14