Nested np.where

后端 未结 3 1120
清酒与你
清酒与你 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:39

    I would recommend you using numpy.select if you have very nested operations.

    df = pd.DataFrame({
        "S": [1, 1, 2, 2],
        "A": [1, 0, 1, 0]
    })
    
    # you could of course combine the clause (1, 4) and (2, 3) with the '|' or operator
    df['RESULT'] = np.select([
        (df.S == 1) & (df.A == 1),
        (df.S == 1) & (df.A == 0),
        (df.S == 2) & (df.A == 1),
        (df.S == 2) & (df.A == 0)
    ], [1, 0, 0, 1])
    

提交回复
热议问题