Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I have a dataframe (df) that looks like:

date                 A 2001-01-02      1.0022 2001-01-03      1.1033 2001-01-04      1.1496 2001-01-05      1.1033  2015-03-30    126.3700 2015-03-31    124.4300 2015-04-01    124.2500 2015-04-02    124.8900 

For the entire time-series I'm trying to divide today's value by yesterdays and log the result using the following:

df["B"] = math.log(df["A"] / df["A"].shift(1)) 

However I get the following error:

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

How can I fix this? I've tried to cast as float using:

df["B"] .astype(float) 

But can't get anything to work.

like image 760
Stacey Avatar asked Mar 23 '17 22:03

Stacey


People also ask

How do you convert a series to a float in Python?

We can convert a string to float in Python using the float() function.

Why can't I convert a string to a float?

The Python "ValueError: could not convert string to float" occurs when we pass a string that cannot be converted to a float (e.g. an empty string or one containing characters) to the float() class. To solve the error, remove all unnecessary characters from the string.

How do pandas change objects to float?

Use pandas DataFrame. astype() function to convert column from string/int to float, you can apply this on a specific column or on an entire DataFrame. To cast the data type to 54-bit signed float, you can use numpy. float64 , numpy.


1 Answers

You can use numpy.log instead. Math.log is expecting a single number, not array.

like image 175
user3582076 Avatar answered Sep 21 '22 12:09

user3582076