0

I have a numpy array which got derived from pandas. I am trying to do np.log (natural logarithm) on each of its elements and it is giving me the error.

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

The array looks something like this.

[5.810785984999995 5.666261181666755 5.577470475833309 7.967268425833254
 8.298006562222156 8.974100307777746 8.553072009444406 9.059574381388813
 9.055145143654158 8.770924936944482 8.52566836194444 8.21766430611109]

The array came from a pandas dataframe using the following code: (just for reference as per requested in comments)

flag = df.iloc[0:12,7].to_numpy()

The error is happening when I try

print (np.log(flag))

However when I try something like

a = np.array([1.35,2.49,3.687])
print (np.log(a))

It works fine. These are still float datatypes? So I am unable to figure out what the issue is, and how I can remedy it.

At the end of the day I am looking to get the natural logarithm of my array.

Jesh Kundem
  • 960
  • 3
  • 18
  • 30
  • 1
    Do you have a float variable called `np` that's shadowing the numpy import? Verify the data type of the variable that's supposed to be a numpy array and/or post the offending code showing where it's throwing the exception. – Woodford Jul 10 '23 at 23:15
  • @Woodford I do not have a float variable called np. Its basically import numpy as np. – Jesh Kundem Jul 10 '23 at 23:18
  • 2
    That's a object dtype array. Change it to float dtype. – hpaulj Jul 10 '23 at 23:21
  • I don't understand how `np.log()` could have the stated error, when `np.array()` works fine... – John Gordon Jul 11 '23 at 00:11
  • For object dtype arrays, `numpy` tries to do `[x.log() for x in arr]`, That is it tries to apply a `log` method to each element. That rarely works since few classes implement a log method. Same for functions like `sin`. Operators like `+` translate to `x.__add__(y)`, which often works. `pandas` readily makes columns `object` dtype (without warning). – hpaulj Jul 11 '23 at 01:05

1 Answers1

2

It seems that the elements in your array are not of the appropriate data type for the np.log function. Although the elements in your array may appear to be floats, they might have a different data type causing the error.

You can try converting the elements in your array explicitly to the float data type using astype(float) before applying the log:

flag = df.iloc[0:12, 7].to_numpy().astype(float)
np.log(flag)
jared
  • 4,165
  • 1
  • 8
  • 31
Norhther
  • 545
  • 3
  • 15
  • 35
  • The problem lies in how numpy applies a function like `log` to each element of an object dtype array. Math on that kind of array is hit or miss, and this cast it's a miss. – hpaulj Jul 11 '23 at 03:30