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
#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
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply


Messages In This Thread
RE: How to define a function that calculates the BMI from dataframe - by volcano63 - May-30-2019, 03:35 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  function returns dataframe as list harum 2 1,404 Aug-13-2022, 08:27 PM
Last Post: rob101
  Struggling for the past hour to define function and call it back godlyredwall 2 2,220 Oct-29-2020, 02:45 PM
Last Post: deanhystad
  Help with define a def function Omer_ 3 2,164 Sep-20-2020, 06:59 PM
Last Post: Omer_
  How to define a function to create a resorted list? sparkt 6 2,821 Aug-08-2020, 04:10 PM
Last Post: sparkt
  Cant define turtle color with function argument Wrightys99 2 2,254 Apr-22-2020, 01:43 PM
Last Post: Wrightys99
  How to define two functions run simultaneously within a function? Alberto 4 4,039 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