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'])
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With