Python Forum
Pass 2 columns via loc to lambda in pandas
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Pass 2 columns via loc to lambda in pandas
#1
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!
Reply
#2
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Pass an object to a class, then make an object of it and pass again TomasAm 11 4,515 Nov-09-2020, 04:47 PM
Last Post: buran
  pandas dataframe substracting columns: key error metalray 2 7,027 Feb-24-2017, 07:59 AM
Last Post: metalray

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020