如果你有多个不同字符串类型的numpy数组,例如:
In [411]: x1.dtype
Out[411]: dtype('S3')
In [412]: x2.dtype
Out[412]: dtype('<U3')
In [413]: x3.dtype
Out[413]: dtype('>U5')
有什么方法可以检查它们是否是全部字符串,而不必显式地与每个单独的类型进行比较?
例如,我想做
In [415]: x1.dtype == <something>
Out[415]: True
In [416]: x2.dtype == <something> # same as above
Out[416]: True
In [417]: x3.dtype == <something> # same as above
Out[417]: True
与 str
= no bueno 相比:
In [410]: x3.dtype == str
Out[410]: False
最佳答案
一种方法是使用 np.issubdtype
与 np.character
:
np.issubdtype(your_array.dtype, np.character)
例如:
>>> np.issubdtype('S3', np.character)
True
>>> np.issubdtype('<U3', np.character)
True
>>> np.issubdtype('>U5', np.character)
True
这是取自 NumPy 文档的 NumPy dtype 层次结构(如图所示!)。如果您想检查常见的数据类型类,这非常有帮助:
如您所见,np.str_
和 np.unicode_
都是“子类”np.character
。
关于python - 与 numpy 进行通用字符串比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45837456/