Apply function on different columns as defined - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: Apply function on different columns as defined (/thread-18819.html) |
Apply function on different columns as defined - DavidGG - Jun-02-2019 I have a function that returns the BMI from a given dataframe with columns 'Weight' and 'Height' Here is the function: def BMI(data): return data['Weight']/(data['Height']**2)Now, i added new column 'Height In Meters' to the dataframe 'data' with: data['Height In Meters']=data['Height']/100What 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. RE: Apply function on different columns as defined - ichabod801 - Jun-02-2019 try: data['BMI'] = data[['Weight', 'Height In Meters']].rename(columns = ['Weight', 'Height']).apply(BMI, axis = 1) RE: Apply function on different columns as defined - DavidGG - Jun-02-2019 (Jun-02-2019, 10:30 AM)ichabod801 Wrote: try: Thank you for trying to help. I still get an unclear error message when running the code:
RE: Apply function on different columns as defined - ichabod801 - Jun-02-2019 Do you have two things named BMI? That error makes it look like you named a list the same thing as your function. RE: Apply function on different columns as defined - DavidGG - Jun-03-2019 (Jun-02-2019, 10:05 PM)ichabod801 Wrote: Do you have two things named BMI? That error makes it look like you named a list the same thing as your function. My function is called BMI, and the column i would like to add to the dataframe also called 'BMI'. Any other suggestions? RE: Apply function on different columns as defined - ichabod801 - Jun-03-2019 Try renaming your function. At the time that line executes, BMI is a list. Maybe that's getting done in the pandas code somewhere. RE: Apply function on different columns as defined - vivekirti - Sep-04-2019 Hi I am also facing the same issue. I have a dataframe named with columns: label,text I defined function as below: def split_tokens(text): message = text.str.lower() word_tokens = word_tokenize(message) return word_tokensI am applying this function on a new dataframe column as below imdb['tokenized_message'] = imdb[['text']].apply(split_tokens,axis=1)But when I execute this function I get error with message: Quote:TypeError: ('expected string or bytes-like object', 'occurred at index 0') Can anyone please help. Thanks |