如何检查类数组(或标量)对象的数据类型是否为浮点数

How do I check if the dtype of an array-like (or scalar) object is a float

这看起来应该超级简单,但我却找不到答案。我已经进行了一系列 google 搜索来寻找答案,但感觉没有任何结果真正回答了我的问题,也许我只是在搜索错误的东西?请帮助:

我正在写一个函数:

def cheese(array_like, *args, **kwargs):
    if dtype_of_(array_like) is float:
        return "macaroni"

dtype_of_(array_like) is float 部分显然不是功能代码,只是我写的一些代码,目的是让您了解我要完成的工作。

我需要的是检查输入是可迭代的浮点数(任何类型的浮点数)还是浮点数。 IE。输入“array_like”可以是任何可以转换为 numpy 数组的可迭代对象,甚至可以是 0 维数组或标量。

我发现了这个看似非常相似的问题 ,但我觉得它没有回答我的问题。

我也发现了另一个类似的问题 here,但这只涉及标量,而不是数组..

到目前为止我所做的是:

def cheese(array_like, *args, **kwargs):
    np.array(array_like, copy=False).dtype == np.floating:
        return "macaroni"

但是虽然这有效,但它也给了我一个弃用警告:

DeprecationWarning: Converting np.inexact or np.floating to a dtype is deprecated. The current result is float64 which is not strictly correct. if np.array(array_like, copy=False).dtype == np.floating:

我想你想要 np.issubdtype:

In [871]: np.issubdtype(np.array([1.23,3]).dtype, np.float64)
Out[871]: True
In [872]: np.issubdtype(np.array([1.23,3]).dtype, np.floating)
Out[872]: True
In [873]: np.issubdtype(np.array([1.23,3]).dtype, np.inexact)
Out[873]: True
In [874]: np.issubdtype(np.array([1,3]).dtype, np.floating)
Out[874]: False
In [875]: np.issubdtype(np.array(34.3).dtype, np.floating)
Out[875]: True

我以前没用过这个,但记得 release notes 有一些关于 dtype.

测试的条目

https://numpy.org/doc/stable/release/1.20.0-notes.html#isinstance-dtype-np-dtype-and-not-type-dtype-is-not-np-dtype

https://numpy.org/doc/stable/release/1.19.0-notes.html#issubdtype-no-longer-interprets-float-as-np-floating

我还没有弄清楚所有细节,但我认为一个主要问题是您正在尝试测试不同种类的东西。

In [885]: type(np.array(1.23).dtype)
Out[885]: numpy.dtype[float64]
In [886]: type(np.floating)
Out[886]: type

数组的dtype是一个dtype对象。但是 np.floating 实际上是一个函数,虽然只有 np.float64(12.23) 可以这样使用。

In [889]: np.float64.__mro__
Out[889]: 
(numpy.float64,
 numpy.floating,
 numpy.inexact,
 numpy.number,
 numpy.generic,
 float,
 object)

np.float64 等函数可用于创建具有特定 dtype 的 numpy 对象和数组,以及用于测试。但是 == 测试实际上涉及一些幕后等效性,这对 python 级别的用户来说并不明显。