Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply lambda function on multiple columns using pandas

Tags:

python

pandas

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!

like image 362
Olive Avatar asked Sep 14 '26 06:09

Olive


1 Answers

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)
like image 127
aaossa Avatar answered Sep 15 '26 20:09

aaossa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!