Search code examples
pythonpandasdataframeformula

Make two conditions and it returns a column with its result in Pandas


enter image description hereI need to create a new column that meets the following conditions. in pandas

this is my current dataframe

Ruote   B   C   D        E
R1    115   1   150     -35
R2    155   1   150     5
R3   155    6   150     5

New column named F

Ruote   B   C   D    E   F
R1     115  1   150 -35  0
R2     155  1   150  5   1
R3     155  6   150  5   5

Example of the conditions that column F must satisfy

IF   “E” <= 0 , Put  0
IF “C “<= “E” Put “C “on the contrary Put  “E”

Solution

  • The equivalent of your Excel formula is:

    import numpy as np
    
    np.where(df['E'].lt(0), 0, np.minimum(df['C'], df['E']))
    

    Or, easier, if your goal is to have the minimum of C/E but never below 0:

    df['F'] = np.minimum(df['C'], df['E']).clip(lower=0)
    

    Output:

      Ruote    B  C    D   E  F
    0    R1  115  1  150 -35  0
    1    R2  155  1  150   5  1
    2    R3  155  6  150   5  5