关于`np.log`的问题

huangapple go评论70阅读模式
英文:

Issues with np.log

问题

我有一个从pandas派生出来的numpy数组。
我正在尝试对其每个元素进行np.log(自然对数),但出现错误。

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

数组看起来是这样的。

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

该数组来自一个pandas数据帧,使用以下代码:(仅供参考,根据评论的要求)

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

当我尝试时发生错误

print (np.log(flag))

然而,当我尝试类似于

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

它正常工作。这些仍然是浮点数据类型吗?所以我无法弄清楚问题是什么,以及如何解决它。

最终,我希望得到数组的自然对数。

英文:

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.

答案1

得分: 2

似乎您的数组中的元素不是np.log函数所需的适当数据类型。虽然您的数组中的元素可能看起来是浮点数,但它们可能具有不同的数据类型,从而导致错误。

您可以尝试在应用对数之前,将数组中的元素明确转换为浮点数据类型,使用astype(float)

flag = df.iloc[0:12, 7].to_numpy().astype(float)
np.log(flag)
英文:

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)

huangapple
  • 本文由 发表于 2023年7月11日 07:09:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76657822.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定