2024-04-25 15:20:36 发布
网友
如何检查numpy数据类型是否为整数?我试过:
issubclass(np.int64, numbers.Integral)
但它给出了False。
False
更新:它现在给出True。
True
Numpy有一个类似于类层次结构的数据类型层次结构(标量类型实际上有一个真实的类层次结构,它反映了数据类型层次结构)。可以使用np.issubdtype(some_dtype, np.integer)来测试数据类型是否为整数数据类型。请注意,与大多数使用dtype的函数一样,np.issubdtype()将其参数转换为dtype,因此可以使用任何可以通过np.dtype()构造函数生成dtype的函数。
np.issubdtype(some_dtype, np.integer)
np.issubdtype()
np.dtype()
http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html#specifying-and-constructing-data-types
>>> import numpy as np >>> np.issubdtype(np.int32, np.integer) True >>> np.issubdtype(np.float32, np.integer) False >>> np.issubdtype(np.complex64, np.integer) False >>> np.issubdtype(np.uint8, np.integer) True >>> np.issubdtype(np.bool, np.integer) False >>> np.issubdtype(np.void, np.integer) False
在未来的numpy版本中,我们将确保标量类型注册到适当的numbersABCs。
numbers
基于前面的回答和评论,我决定使用dtype对象的type属性和Python的内置issubclass()方法以及numbers模块:
dtype
type
issubclass()
import numbers import numpy assert issubclass(numpy.dtype('int32').type, numbers.Integral) assert not issubclass(numpy.dtype('float32').type, numbers.Integral)
注意np.int64不是一个dtype,而是一个Python类型。如果您有一个实际的dtype(通过数组的dtype字段访问),那么可以使用您发现的np.typecodesdict:
np.int64
np.typecodes
my_array.dtype.char in np.typecodes['AllInteger']
如果只有np.int64这样的类型,则可以首先获取与该类型相对应的数据类型,然后按上述方式进行查询:
>>> np.dtype(np.int64).char in np.typecodes['AllInteger'] True
Numpy有一个类似于类层次结构的数据类型层次结构(标量类型实际上有一个真实的类层次结构,它反映了数据类型层次结构)。可以使用
np.issubdtype(some_dtype, np.integer)
来测试数据类型是否为整数数据类型。请注意,与大多数使用dtype的函数一样,np.issubdtype()
将其参数转换为dtype,因此可以使用任何可以通过np.dtype()
构造函数生成dtype的函数。http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html#specifying-and-constructing-data-types
在未来的numpy版本中,我们将确保标量类型注册到适当的
numbers
ABCs。基于前面的回答和评论,我决定使用
dtype
对象的type
属性和Python的内置issubclass()
方法以及numbers
模块:注意
np.int64
不是一个dtype,而是一个Python类型。如果您有一个实际的dtype(通过数组的dtype
字段访问),那么可以使用您发现的np.typecodes
dict:如果只有
np.int64
这样的类型,则可以首先获取与该类型相对应的数据类型,然后按上述方式进行查询:相关问题 更多 >
编程相关推荐