Python Forum
How to define a function that calculates the BMI from dataframe
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to define a function that calculates the BMI from dataframe
#1
I need to define a function that will calculate and return out of dataframe that includes columns "Height" and "Weight", the BMI of each row.

Here is the code that i wrote:

def BMI(DataFrame):
    df=pd.DataFrame
    return 'Weight'/'Height'**2
But when I try to run that function with:
data.apply(BMI,axis=1)
when "data" is my dataframe,

the result is an error:
Error:
Traceback (most recent call last): File "<input>", line 1, in <module> File "D:\Python Projects\venv\lib\site-packages\pandas\core\frame.py", line 6487, in apply return op.get_result() File "D:\Python Projects\venv\lib\site-packages\pandas\core\apply.py", line 151, in get_result return self.apply_standard() File "D:\Python Projects\venv\lib\site-packages\pandas\core\apply.py", line 257, in apply_standard self.apply_series_generator() File "D:\Python Projects\venv\lib\site-packages\pandas\core\apply.py", line 286, in apply_series_generator results[i] = self.f(v) File "<input>", line 3, in BMI TypeError: ("'type' object is not subscriptable", 'occurred at index 0')
What went wrong with my code?
Reply
#2
#!/usr/bin/python3
import pandas as pd

data = [
  { 'h': 1.80, 'w': 80 },
  { 'h': 1.70, 'w': 90 },
  { 'h': 1.60, 'w': 60 },
]

df = pd.DataFrame(data)
print(df)
print("------------------")

def BMI(data):
    return data['w'] / data['h']**2

df['bmi'] = df.apply(BMI, axis=1)
print(df)

Output:
h w 0 1.8 80 1 1.7 90 2 1.6 60 ------------------ h w bmi 0 1.8 80 24.691358 1 1.7 90 31.141869 2 1.6 60 23.437500
Reply
#3
(May-30-2019, 02:34 PM)heiner55 Wrote:
#!/usr/bin/python3
import pandas as pd

data = [
  { 'h': 1.80, 'w': 80 },
  { 'h': 1.70, 'w': 90 },
  { 'h': 1.60, 'w': 60 },
]

df = pd.DataFrame(data)
print(df)
print("------------------")

def BMI(data):
    return data['w'] / data['h']**2

df['bmi'] = df.apply(BMI, axis=1)
print(df)

Output:
h w 0 1.8 80 1 1.7 90 2 1.6 60 ------------------ h w bmi 0 1.8 80 24.691358 1 1.7 90 31.141869 2 1.6 60 23.437500

There are better ways with pandas - you can operate on rows/columns directly
df['bmi'] = df.w / df.h ** 2
Output:
h w bmi 0 1.8 80 24.691358 1 1.7 90 31.141869 2 1.6 60 23.437500
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with define a def function Omer_ 3 139 Sep-20-2020, 06:59 PM
Last Post: Omer_
  How to define a function to create a resorted list? sparkt 6 336 Aug-08-2020, 04:10 PM
Last Post: sparkt
  Cant define turtle color with function argument Wrightys99 2 325 Apr-22-2020, 01:43 PM
Last Post: Wrightys99
  How to define two functions run simultaneously within a function? Alberto 4 1,603 Feb-06-2018, 10:08 PM
Last Post: Alberto

Forum Jump:

User Panel Messages

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