为什么我得到'循环ufunc不支持参数0类型int'错误numpy.exp?

ghhaqwfi  于 2023-04-21  发布在  其他
关注(0)|答案(4)|浏览(307)

我有一个dataframe,我想对列中的行的子集执行指数计算。我已经尝试了三个版本的代码,其中两个工作。但我不明白为什么一个版本给我的错误。

import numpy as np

版本1(工作)

np.exp(test * 1.0)

版本2(工作)

np.exp(test.to_list())

版本3(错误)

np.exp(test)

它显示以下错误:

AttributeError                            Traceback (most recent call last)
AttributeError: 'int' object has no attribute 'exp'

The above exception was the direct cause of the following exception:

TypeError                                 Traceback (most recent call last)
<ipython-input-161-9d5afc93942c> in <module>()
----> 1 np.exp(pd_feature.loc[(pd_feature[col] > 0) & (pd_feature[col] < 700), col])

TypeError: loop of ufunc does not support argument 0 of type int which has no callable exp method

测试数据通过以下方式生成:

test = pd.loc[(pd['a'] > 0) & (pd['a'] < 650), 'a']

测试中的数据仅为:

0      600
2      600
42     600
43     600
47     600
60     600
67     600
Name: a, dtype: Int64

其数据类型为:

<class 'pandas.core.series.Series'>

但是,如果我尝试生成一个虚拟数据集,它会工作:

data = {'a':[600, 600, 600, 600, 600, 600, 600], 'b': ['a', 'a', 'a', 'a', 'a', 'a', 'a']} 

df = pd.DataFrame(data) 

np.exp(df.loc[:,'a'])

你知道为什么我会看到这个错误吗?非常感谢。

nhn9ugyo

nhn9ugyo1#

我猜你的问题发生是因为一些NumPy函数显式地需要float类型的参数。然而,你的代码np.exp(test)的类型是int
尝试将其强制为float

import numpy as np

your_array = your_array.astype(float)
output = np.exp(your_array)

# OR

def exp_test(x)
  x.astype(float)
  return np.exp(x)

output = exp_test(your_array)
7z5jn7bk

7z5jn7bk2#

问题的根源在吉明的回答中是正确的
我猜你的问题发生是因为一些numpy函数需要显式的浮点型参数,而你对np.exp(test)这样的代码的使用将int数据放入参数中。
然而,他的解决方案对我不起作用,所以我稍微调整了一下,让它对我起作用

your_array = your_array.astype(float)
output = np.exp(your_array)
lf5gs5x2

lf5gs5x23#

虽然这个问题已经得到了充分的回答,但我想分享我在这个问题上的经验,希望能更多地了解这类问题以及导致它们的原因。从我收集的信息来看,这个问题与“numpy vs non-numpy数据类型”有关。下面是一个最小的例子:

import numpy as np

arr_float = np.array([1., 2., 3.], dtype=object)
arr_float64 = arr_float.astype(float)  # The solution proposed in other answers
np.exp(arr_float)  # This throws the TypeError
np.exp(arr_float64)  # This works!

最终得到一个“浮点型”的对象类型数组可能有各种原因,可能与从DataFrame中提取的分析数据有关,其中数据存储在错误的类型中(由于存在不可转换的条目),或者在numpy和另一个介质(如pandas)之间进行一些来回转换。
总之-小心数据类型floatnp.float64

7bsow1i6

7bsow1i64#

test = pd.loc[(pd['a'] > 0) & (pd['a'] < 650), 'a'].values

相关问题