如何解决 Python 中的错误"module 'numpy' has no attribute 'float'"?



我使用的是NumPy 1.24.0。

在运行这个示例代码行时,

import numpy as np
num = np.float(3)

我得到这个错误:

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'

我该如何修复它?

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

  • NumPy1.20(发布说明)已弃用的numpy.float,numpy.int和类似的别名,导致它们发出弃用警告

  • NumPy1.24(发行说明)完全删除了这些别名,导致错误

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

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

……

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

对于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或更低(如其他一些答案所建议的),同时等待依赖赶上。或者,您可以自己创建一个补丁并打开一个pull请求,或者在您自己的代码中对依赖项进行补丁。

1.24版本:

不赞成使用别名np。对象,np。bool, np。浮点,np,复数,np。而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

尽量使用简单的"猴子路径"。添加像

这样的行
np.float = float    

np.int = int    

模块'numpy'没有属性'int'

np.object = object    

模块'numpy'没有属性'object'

np.bool = bool    

等等…(如果最新Numpy版本有问题)

我删除了NumPy .py,然后更新了我的NumPy安装。它工作!

注意:NumPy版本1.23.3

我通过更新我的" openpyxl ";使用

{pip install --upgrade openpyxl}

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

我在读取.xlsx文件时遇到了同样的问题。您可以将其转换为csv,这将解决问题。然而,为了更新numpy,有时你需要获得numpy包的目录:

import numpy
print(numpy.__path__)

要更新它,可以使用下面的代码:

pip install numpy --upgrade

你也可以查看这个页面:如何升级NumPy?

numpy-1.24.3

链接:https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations

您可以使用以下任何一个

来代替np.float
>>float
>>numpy.float64
>>numpy.double
>>numpy.float_

相关内容

最新更新