Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Float' object has no attribute 'log'

I have a time series with price information in column price. When I tried to create a new column ln_price by taking the ln of column price I got an error:

AttributeError: 'float' object has no attribute 'log'

Can someone help me understand why this would be and how it can be fixed?

Thanks!

df['ln_price'] = np.log(df['price'])
like image 354
Tony Avatar asked Jul 02 '19 21:07

Tony


1 Answers

As pointed out by warren-weckesser this can also happen if you use dtype object (and in fact this is likelier the issue you are facing):

>>> s = pd.Series([1.0], dtype='object')
>>> s
0    1
dtype: object
>>> np.log(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'float' object has no attribute 'log'

You can address this by setting the dtype to float explicitly:

>>> np.log(s.astype('float64'))
0    0.0
dtype: float64

In your case:

np.log(df['price'].astype('float'))

Note: You can have more control using to_numeric.


First/alternative answer:

You have a float variable np in scope.

The problem is that:

import numpy as np
np = 1
np.log

is perfectly valid python.

>>> import numpy as np
>>> np = 1.
>>> np.log
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'float' object has no attribute 'log'

The solution is not to use np are a variable name, or other popular import abbreviations pd or dt etc. You can pick this kind of error up using a linter.

like image 120
Andy Hayden Avatar answered Oct 14 '22 10:10

Andy Hayden