Python Forum

Full Version: Pass 2 columns via loc to lambda in pandas
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone,

I am working on something that calculates a bmi. I have it solved a certain way but my friend told me it was non pythonic and to solve it using loc and lambda.

I have spent the day working on this and have solved other ones with loc & lambda but this one is more challenging as it requires passing multiple values to lambda.

Here is how I solved it originally

import pandas as pd

df = pd.DataFrame({'name': ['Karim', 'House', 'Leon', 'David'],
                   'role': ['Director', 'Director', 'Data Scientist', 'Data Scientist'],
                   'height': [72, 70, 68, 73],
                   'weight': [165, 190, 170, 205]})

BMI1 = (df['weight'] / (df['height'] * df['height'])) * 703
df['BMI']=BMI1
Now with using loc and lambdas I am confused on how to get the two columns (weight and height) into lambda.

Here is what I am working with:

dc.loc[:, 'bmi'] = df.loc[:, ['weight', 'height']].apply(lambda x, y: (x / y * y) * 703)
No idea how to push the two columns into x & y.

I can't seem to find the synatx via googling or reading about lambda or loc in books.

Any help appreciated!
Maybe he thinks its more pythonic because lambda can be used with for instance the map function and you could avoid making a loop yourself(?).

This page has a pretty good description i think:
https://www.python-course.eu/lambda.php