Search code examples
pythonpandasdataframemultiple-conditions

PANDAS : Assigning a value for each row in certain column based on multiple if condition


I'm really new to python codes and having trouble with applying some of the answers for similar questions for my own case. Please help

So I have a dataframe with Column A and B, with numerous rows

Both contains negative and positive numbers, and I'm trying to make a new Column C with following conditions

If "Value of row 1, Column A is less than 0" & "Value of row 1, Column B is less than 0", return -100 in "row 1, Column C"

Elif "Value of row 1, Column A is less than 0" & "Value of row 1, Column B is greater than 0", return 100 in "row 1, Column C"

Elif "Value of row 1, Column A is greater than 0" & "Value of row 1, Column B is less than 0", return 100 in "row 1, Column C"

Else : return (Column A.Value / Column B.Value) in Column C

Thanks a lot


Solution

  • I think you are looking for np.select:

    condlist = [(df['A'] < 0) & (df['B'] < 0),
                (df['A'] < 0) & (df['B'] > 0),
                (df['A'] > 0) & (df['B'] < 0)]
    
    choicelist = [-100, 100, 100]
    
    default = df['A'] / df['B']
    
    df['C'] = np.select(condlist, choicelist, default)
    

    Output:

    >>> df
              A          B           C
    0 -0.002639  -1.374507 -100.000000
    1 -0.696428   9.923431  100.000000
    2  1.410547   3.804043    0.370802
    3  1.504908   2.701486    0.557067
    4  1.867486   1.889067    0.988576
    5 -0.451066 -11.529716 -100.000000
    6  5.713800  -7.678271  100.000000
    7 -4.318760   5.082725  100.000000
    8  5.169819  -4.122461  100.000000
    9  0.094524  -1.916718  100.000000
    

    Setup a MRE

    import pandas as pd
    import numpy as np
    
    np.random.seed(2022)
    df = pd.DataFrame(np.random.normal(0, 5, (10, 2)), columns=['A', 'B'])