-1

I have a table and I want to replace column values with other columns values based on a condition:

Table:

A B C D E
x 1 test fool bar
y 3 test fool bar

If column C contains the word test -> value should be replaced with content of column A

If column D contains the word fool -> value should be replaced with content of column B

A B C D E
x 1 x 1 bar
y 3 y 3 bar

How can I create this table?

honeymoon
  • 2,400
  • 5
  • 34
  • 43

1 Answers1

2

We can use np.where here:

df["C"] = np.where(df["C"] == "test", df["A"], df["C"])
df["D"] = np.where(df["D"] == "fool", df["B"], df["D"])
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360