David
David

Reputation: 23

How to apply defined function on other column than defined

I have a function that returns the BMI from a given dataframe with columns 'Weight' and 'Height' Here is the function:

def BMI(dataframe):
    return dataframe['Weight'] / (dataframe['Height']**2)

I added new column 'Height In Meters' to the dataframe 'data' with:

data['Height In Meters'] = data['Height']/100

What i would like to do next, is to apply the original function on the dataframe 'data', but instead of using the column 'Height', the calculation would be by using the new column 'Height In Meters'.

the result should be a new column called 'BMI' in the dataframe 'data', that shows for each row the calculation using 'Height In Meters'.

I tried:

data['BMI'] = data[['Weight','Height In Meters']].apply(BMI,axis=1)

But that doesn't seem to work.

Upvotes: 0

Views: 48

Answers (1)

razdi
razdi

Reputation: 1440

You could pass the column names as arguments:

def BMI(dataframe, col1, col2):
    return dataframe[col1] / (dataframe[col2]**2)

a = data.apply(BMI, args=('Weight', 'Height'), axis=1)

data['Height In Meters'] = data['Height']/100

b = data.apply(BMI, args=('Weight', 'Height In Meters'), axis=1)

Upvotes: 2

Related Questions