问题描述
我必须从具有int,float或复数的类似数组的数据中创建一个 numpy.ndarray
.
I have to create a numpy.ndarray
from array-like data with int, float or complex numbers.
我希望使用 numpy.asarray
函数来做到这一点.
I hope to do it with numpy.asarray
function.
我不想给它一个严格的 dtype
参数,因为我想将复杂的值转换为 complex64
或 complex128
,浮点数到 float32
或 float64
等
I don't want to give it a strict dtype
argument, because I want to convert complex values to complex64
or complex128
, floats to float32
or float64
, etc.
但是,如果我只是简单地运行 numpy.ndarray(some_unknown_data)
并查看其结果的dtype,我如何理解数据是数字的,而不是对象,字符串或其他东西?
But if I just simply run numpy.ndarray(some_unknown_data)
and look at the dtype of its result, how can I understand, that the data is numeric, not object or string or something else?
推荐答案
您可以检查数组的dtype是否为 np.number
的子dtype.例如:
You could check if the dtype of the array is a sub-dtype of np.number
. For example:
>>> np.issubdtype(np.complex128, np.number)
True
>>> np.issubdtype(np.int32, np.number)
True
>>> np.issubdtype(np.str_, np.number)
False
>>> np.issubdtype('O', np.number) # 'O' is object
False
基本上,这只是检查dtype是否在 NumPy dtype层次结构:
Essentially, this just checks whether the dtype is below 'number' in the NumPy dtype hierarchy:
这篇关于numpy.asarray:如何检查其结果dtype是否为数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!