Home > Software engineering >  How to apply lambda function on multiple columns using pandas
How to apply lambda function on multiple columns using pandas

Time:03-06

I always convert the columns into floats, by

prices['Open'] = prices['Open'].apply(lambda x: float(x))
prices['Close'] = prices['Close'].apply(lambda x: float(x))
prices['High'] = prices['High'].apply(lambda x: float(x))
prices['Low'] = prices['Low'].apply(lambda x: float(x))
prices['Volume'] = prices['Volume'].apply(lambda x: float(x))
prices['Market cap'] = prices['Market cap'].apply(lambda x: float(x))

I want to be able to do this in one line, i tried using

prices[['Open', 'Close', 'High', 'Low', 'Volume', 'Market cap']] = prices[['Open', 'Close', 'High', 'Low', 'Volume', 'Market cap']].apply(lambda x: float(x))

but it gives me an error msg:

TypeError: cannot convert the series to <class 'float'>

any help will be appreciated!

CodePudding user response:

You're looking for .applymap:

prices[list_of_columns].applymap(lambda x: float(x))

Also, if you're really trying to just convert the values into floats, just use .astype:

prices[list_of_colums] = prices[list_of_columns].astype(float)

CodePudding user response:

You can use astype() to convert the data type to float in a single line:

prices = prices.astype({"Open":'float', "Close":'float', "Low":'float', "Volume":'float', "Market cap":'float'})  
  • Related