Nested np.where

后端 未结 3 1122
清酒与你
清酒与你 2021-01-22 03:56

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

3条回答
  •  醉梦人生
    2021-01-22 04:50

    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
    

    output:

    |   | S | A | Result |
    |---|---|---|--------|
    | 0 | 1 | 1 | 1      |
    | 1 | 1 | 0 | 0      |
    | 2 | 2 | 1 | 0      |
    | 3 | 2 | 0 | 1      |
    

提交回复
热议问题