0

I have created an empty column named url. I want to set the value of the url in each row depending on the value of target. If the target is 0 then I will use the value of urlA on url for that row. Else if the target is 1 then I will use the value of urlB on the url for that row. For illustration, this is the table before.

   url   urlA   urlB    target
1         x1     y1       0
2         x2     y2       1
3         x3     y3       1
4         x4     y4       0

After:

    url   urlA   urlB    target
1   x1      x1     y1       0
2   y2      x2     y2       1
3   y3      x3     y3       1
4   x4      x4     y4       0
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Mervyn Lee
  • 1,957
  • 4
  • 28
  • 54
  • Possible duplicate of [Pandas conditional creation of a series/dataframe column](https://stackoverflow.com/questions/19913659/pandas-conditional-creation-of-a-series-dataframe-column) – Amit Gupta Oct 22 '19 at 04:18

1 Answers1

2

Use np.where:

df["url"] = np.where(df["target"]==1, df["urlB"], df["urlA"])

#
  url urlA urlB  target
0  x1   x1   y1       0
1  y2   x2   y2       1
2  y3   x3   y3       1
3  x4   x4   y4       0
Henry Yik
  • 22,275
  • 4
  • 18
  • 40