如何解决Python中的错误“模块'numpy'没有属性'float'”?

Naw*_*rma 63 python numpy

我正在使用 NumPy 1.24.0。

运行此示例代码行时,

import numpy as np
num = np.float(3)
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

Traceback (most recent call last):   File "<stdin>", line 1, in <module>   File "/home/ubuntu/.local/lib/python3.8/site-packages/numpy/__init__.py", line 284, in __getattr__
    raise AttributeError("module {!r} has no attribute " AttributeError: module 'numpy' has no attribute 'float'
Run Code Online (Sandbox Code Playgroud)

我该如何修复它?

djv*_*jvg 58

@mattdmo@tdelaney的评论中已经提供了答案:

  • NumPy 1.20 (发行说明)已弃用numpy.floatnumpy.int和类似别名,导致它们发出弃用警告

  • NumPy 1.24 (发行说明)完全删除了这些别名,导致使用它们时出现错误

在许多情况下,您可以简单地将已弃用的 NumPy 类型替换为等效的 Python 内置类型,例如,numpy.float变成“普通” Python float

有关如何处理各种已弃用类型的详细指南,请仔细查看1.20 发行说明中的​​表格和指南:

...

为了给绝大多数情况提供明确的指导,对于类型bool, object, str( 和unicode) ,使用普通版本更短、更清晰,通常是一个很好的替代。如果您希望更明确地了解精度,则可以使用floatand 。complexfloat64complex128

np.int直接替换为或np.int_int很好,并且不会改变行为,但精度将继续取决于计算机和操作系统。如果您想更明确并查看当前的使用情况,您有以下选择:

  • np.int64np.int32准确指定精度。这确保结果不会依赖于计算机或操作系统。
  • np.int_int(默认值),但请注意,这取决于计算机和操作系统。
  • C 类型:np.cint( int), np.int_( long), np.longlong.
  • np.intp在 32 位机器上是 32 位,在 64 位机器上是 64 位。这可能是用于索引的最佳类型。

...

如果您有使用已弃用类型的依赖项,一个快速解决方法是将 NumPy 版本回滚到 1.24 或更低(如其他一些答案中的建议),同时等待依赖项赶上。或者,您可以自己创建补丁并打开拉取请求,或者在您自己的代码中猴子修补依赖项。

  • 我想知道这一更改浪费了多少开发时间。我确定有1000个。非常令人沮丧。 (5认同)

Ser*_*hii 33

在1.24版本中:

别名 np.object、np.bool、np.float、np.complex、np.str 和 np.int 的弃用已过期(引入 NumPy 1.20)。其中一些现在除了引发错误之外还会给出 FutureWarning,因为它们将来会映射到 NumPy 标量。

pip install "numpy<1.24"解决它。

In [1]: import numpy as np

In [2]: np.__version__
Out[2]: '1.23.5'

In [3]: np.float(3)
<ipython-input-3-8262e04d58e1>:1: DeprecationWarning: `np.float` is a deprecated alias for the builtin `float`. To silence this warning, use `float` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.float64` here.
Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations
  np.float(3)
Out[3]: 3.0
Run Code Online (Sandbox Code Playgroud)


小智 14

您可以使用以下猴子补丁来运行依赖项:

np.float = float    
np.int = int   #module 'numpy' has no attribute 'int'
np.object = object    #module 'numpy' has no attribute 'object'
np.bool = bool    #module 'numpy' has no attribute 'bool'
Run Code Online (Sandbox Code Playgroud)


小智 5

我通过使用更新我的“openpyxl”来解决

{pip install --upgrade openpyxl}
Run Code Online (Sandbox Code Playgroud)

尝试读取 Excel 文件时出现错误