Search code examples
pythonpandasdataframelambdamultiple-conditions

Nested Lambda with If conditions Python


I need to create a new column(FinalSL) for my daframe "copieddata1", with the follow condition:

enter image description here

1st step:

If ['defaultstore'] column = 1: then [FinalSL]= 4*['FCST: TOTAL'] column values
if no>  then check if ['SSS'] column is supporting the follow condition(2nd Step):

2nd step:

3*['FCST: TOTAL'] column values < ['SSS'] column values < 4*['FCST: TOTAL'] column values

So I have three possible outcomes:

1st' ['SSS'] < 3*['FCST: TOTAL'] then ['FinalSL']  = 3['FCST: TOTAL']
2nd' 3*['FCST: TOTAL'] < ['SSS'], but 4*['FCST: TOTAL'] < SSS tehn ['FinalSL']  = 3['FCST: TOTAL']
3rd' 3*['FCST: TOTAL'] < ['SSS'] < 4*['FCST: TOTAL'] then ['FinalSL'] = ['SSS']

Then, in summary I believe I have the follow conditions to apply in my code:

if SSS < 3*F then
   FinalSL = 3*F
else
   if 4*F < SSS then
       FinalSL = 3*F
else
    FinalSL = SSS

The I could create the idea for the 1step, but testing with a return the value 2 if the 1st condition from the first step is not true, but in fact this "return 2" should be replaced by the 2nd step conditions.

How can I be creating this ? I created the basic idea using lambda and the method apply:

copiedData1['FinalSL'] = np.where(copiedData1['defaultstore']==1,copiedData1['FCST: TOTAL']*4,2)

It worked, but now I need to do with the rights conditions from the 2nd step.

Any help would be very appreciated! Thanks :)


Solution

  • You could do this with nested np.where()'s. Roughly like this (pseudo-code-ish) answer:

    df['FinalSL'] = np.where(SSS < 3*F, 3*F, np.where(4*F < SSS, 4*F, SSS)))