'Conditional computing on pandas dataframe with an if statement [duplicate]
I have the following df:
A B C
100 2 3
-100 2 3
I want a new column that multiplies either column B or C by the value of column A:
if A<0:
D = A*B
if A>=0:
D = A*C
So in the end I get:
A B C D
100 2 3 200
-100 2 3 -300
Solution 1:[1]
You could run a lambda function based on what you are looking like this:
df["D"] = df.apply(lambda row: row["A"] * row["B"] if row["A"] < 0 else row["A"] * row["C"], axis=1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Aidan Donnelly |
