'Float' object has no attribute 'log'

Viewed 15161

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'])
2 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.

The problem is outside of the code that you posted. Your code works. At least if I assume that df is a dict. But I cannot assume anything else, because your question does not specify it.

import numpy as np

df = {'price': 10.0}
df['ln_price'] = np.log(df['price'])

print(df)
{'price': 10.0, 'ln_price': 2.3025850929940459}
Related