Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use lamda and an if in pandas

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks for your help.

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading