Home > Mobile >  How to use lamda and an if in pandas
How to use lamda and an if in pandas

Time:11-26

I'm trying to use the lambda function to calculate some pay rates depending on job type.

Here is part of my code:

Payrate = {
'NH': 14.00,
'W1': 14.00,
'W2': 14.00,
'W3': 14.00,
'M': 14.00,
'NHLC': 14.00,
'E': 14.00,
}

df = df.fillna(0)
df['Total shift hours'] = df['Total shift hours'].astype(int)

df['Hours'] = df['Job'].apply(lambda x: x[Payrate] if x[Payrate]*(x['Total shift hours'])/12.33 else df['Total shift hours'].sum()).round(2)

Job is a column in the data frame that shows us the job type. So what I'm trying to say is, if the Job type matches the jobs in Payrate, multiply the Total shift hours by assigned value of 14 and divide it by 12.33. Else, if it's another job type that's not mentioned in the Payrate dict, take the sum of Total shift hours.

Thanks for your help.

CodePudding user response:

Here is solution without loop in apply by mapping in Series.map with replace missing not matched values by sum:

df['Hours'] = ((df['Job'].map(Payrate) * df['Total shift hours'] / 12.33 )
                  .fillna(df['Total shift hours'].sum()).round(2))
  • Related