pythonnumpynatural-logarithm

Issues with np.log


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.


Solution

  • 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)