np.where not working with multiple conditions?

Viewed 358

I have a dataframe that looks a bit like this:

 | offer_code | column2 | column3
-|------------|---------|--------
0| 123        | X       | NaN
1| 123        | Y       | NaN
2| 456        | X       | X
3| 456        | Y       | X

I'm trying to add a new column which flags as 0 all rows where column3 = NaN OR column2 and column3 match. Everything else should be flagged as 1. So the result should look like this:

 | offer_code | column2 | column3 | flag
-|------------|---------|---------|-----
0| 123        | X       | NaN     | 0
1| 123        | Y       | NaN     | 0
2| 456        | X       | X       | 0
3| 456        | Y       | X       | 1

However, my code just flags every single row as 1. This is the code I'm using; can anyone see where I'm going wrong please?

df["flag"] = np.where(df["column3"].isnull()|df["column2"]==df["column3"],0,1)
1 Answers

Missing parenthesis around the second condition:

df["flag"] = np.where(df["column3"].isnull() |
                      (df["column2"] == df["column3"]), 0, 1)
#                     ^                              ^

Or with eq:

df["flag"] = np.where(df["column3"].isnull() |
                      df['column2'].eq(df['column3']), 0, 1)

df:

   offer_code column2 column3  flag
0         123       X     NaN     0
1         123       Y     NaN     0
2         456       X       X     0
3         456       Y       X     1
Related