Python Forum
Pass 2 columns via loc to lambda in pandas - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Pass 2 columns via loc to lambda in pandas (/thread-8469.html)



Pass 2 columns via loc to lambda in pandas - fad3r - Feb-21-2018

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!


RE: Pass 2 columns via loc to lambda in pandas - glidecode - Feb-22-2018

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