I have the following dataframe:
S A
1 1
1 0
2 1
2 0
I wanted to create a new \'Result\'
column that is calculated based on the val
You should use nested np.where. It is like sql case clause. But be careful when there is nan in the data.
df=pd.DataFrame({'S':[1,1,2,2],'A':[1,0,1,0]})
df['Result'] = np.where((df.S == 1) & (df.A == 1), 1, #when... then
np.where((df.S == 1) & (df.A == 0), 0, #when... then
np.where((df.S == 2) & (df.A == 1), 0, #when... then
1))) #else
df
| | S | A | Result |
|---|---|---|--------|
| 0 | 1 | 1 | 1 |
| 1 | 1 | 0 | 0 |
| 2 | 2 | 1 | 0 |
| 3 | 2 | 0 | 1 |