【问题标题】:Why do I get the 'loop of ufunc does not support argument 0 of type int' error for numpy.exp?为什么我会收到 numpy.exp 的“ufunc 循环不支持 int 类型的参数 0”错误?
【发布时间】:2019-12-12 04:04:59
【问题描述】:

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

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'])

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

【问题讨论】:

  • test 是一个object dtype 数组,试试test.values.astype(float)
  • this answer,但忽略apply的使用,将log10替换为exp

标签: python numpy exponential


【解决方案1】:

我猜你的问题是因为某些 NumPy 函数明确需要 float-type 参数。但是,您的代码 np.exp(test) 的类型为 int

尝试强制为float

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)

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

    • 谢谢玛蒂亚!伟大的 !!它真的对我有用,而 Yoshiaki 的回答不起作用
    【解决方案3】:

    虽然这个问题已经得到了充分的回答,但我还是想分享一下我在这个问题上的经验,希望能对这类问题以及造成这些问题的原因有更多的了解。根据我收集的信息,问题与“numpy 与非 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

    【讨论】:

      【解决方案4】:
      test = pd.loc[(pd['a'] > 0) & (pd['a'] < 650), 'a'].values
      

      【讨论】:

      • 这不会解决问题中的错误。在任何地方都可以使用,原始代码也可以使用。
      • 如果您提供解释为什么这是首选解决方案并解释它是如何工作的,它会更有帮助。我们想要教育,而不仅仅是提供代码。
      猜你喜欢
      • 1970-01-01
      • 2019-11-23
      • 2021-12-07
      • 2020-12-09
      • 2021-09-29
      • 2013-07-17
      • 2021-02-14
      • 1970-01-01
      • 2021-01-21
      相关资源
      最近更新 更多