How to define a function that calculates the BMI from dataframe - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to define a function that calculates the BMI from dataframe (/thread-18759.html) |
How to define a function that calculates the BMI from dataframe - DavidGG - May-30-2019 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'**2But when I try to run that function with: data.apply(BMI,axis=1)when "data" is my dataframe, the result is an error: What went wrong with my code?
RE: How to define a function that calculates the BMI from dataframe - heiner55 - May-30-2019 #!/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)
RE: How to define a function that calculates the BMI from dataframe - volcano63 - May-30-2019 (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) There are better ways with pandas - you can operate on rows/columns directly df['bmi'] = df.w / df.h ** 2
|