为什么我会收到 numpy.exp 的“ufunc 循环不支持 int 类型的参数 0”错误?

use*_*451 18 python numpy exponential

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

import numpy as np
Run Code Online (Sandbox Code Playgroud)

版本 1(工作)

np.exp(test * 1.0)
Run Code Online (Sandbox Code Playgroud)

版本 2(工作)

np.exp(test.to_list())
Run Code Online (Sandbox Code Playgroud)

版本 3(错误)

np.exp(test)
Run Code Online (Sandbox Code Playgroud)

它显示以下错误:

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
Run Code Online (Sandbox Code Playgroud)

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

test = pd.loc[(pd['a'] > 0) & (pd['a'] < 650), 'a']
Run Code Online (Sandbox Code Playgroud)

测试中的数据只是:

0      600
2      600
42     600
43     600
47     600
60     600
67     600
Name: a, dtype: Int64
Run Code Online (Sandbox Code Playgroud)

其数据类型为:

<class 'pandas.core.series.Series'>
Run Code Online (Sandbox Code Playgroud)

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

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'])
Run Code Online (Sandbox Code Playgroud)

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

小智 21

刚看到你的帖子,想回答一下。

我猜你的问题发生是因为一些 numpy 函数需要显式地使用浮点类型参数,而你这样使用代码np.exp(test)int数据放入参数中。

解决方案可能是:

import numpy as np

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

# OR

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

output = exp_test(your_array)

Run Code Online (Sandbox Code Playgroud)

你会检查它是否对你有用吗?我很乐意帮忙。

  • 这个`.float()`方法在哪里定义的?据我所知,numpy 数组没有此方法,而您需要使用“.astype(float)”。 (8认同)

Mat*_*tiH 10

问题的根本原因在 Yoshiaki 的回答中是正确的

我猜你的问题发生是因为一些 numpy 函数需要显式地使用浮点类型参数,而你使用 np.exp(test) 这样的代码将 int 数据放入参数中。

然而,他的解决方案对我不起作用,所以我稍微调整了一下,让它对我有用

your_array = your_array.astype(float)
output = np.exp(your_array)
Run Code Online (Sandbox Code Playgroud)


Dev*_*-iL 6

尽管这个问题已经得到了充分的回答,但我还是想分享一下我在这个问题上的经验,希望能对此类问题及其原因有更多的了解。根据我收集的信息,问题与“numpy 与非 numpy 数据类型”有关。这是一个最小的例子:

\n
import numpy as np\n\narr_float = np.array([1., 2., 3.], dtype=object)\narr_float64 = arr_float.astype(float)  # The solution proposed in other answers\nnp.exp(arr_float)  # This throws the TypeError\nnp.exp(arr_float64)  # This works!\n
Run Code Online (Sandbox Code Playgroud)\n

最终得到“看起来是浮动的”对象类型数组可能有多种原因,可能与从 DataFrame 中提取分析数据有关,其中数据存储的类型不正确(由于存在不可转换的条目),或者numpy 和另一种媒介(如 pandas)之间的一些来回转换。

\n

总之 -小心数据类型float\xe2\x89\xa0 np.float64

\n