Steve4569
Steve4569

Reputation: 21

How to apply a function to a range of columns in dataframe?

I am trying to apply a function to the values in a range of columns in my dataframe, but it shows an error:

This is my dataframe

enter image description here

#define a function to change missing values to NaN
def change_missing(num):
    if (num != None) & (type(num) != int) & (type(num) != float):
        return np.nan
    else:
        return num

Energy.iloc[:,1:4].apply(change_missing)
ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index Energy Supply')

Upvotes: 0

Views: 736

Answers (1)

user17242583
user17242583

Reputation:

You need to use applymap, which calls the specified function for each cell of each column, instead of apply, which calls the specified function for each column only:

Energy.iloc[:,1:4].applymap(change_missing)

Upvotes: 2

Related Questions