python - 与 numpy 进行通用字符串比较

标签 python numpy

如果你有多个不同字符串类型的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.issubdtypenp.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 层次结构(如图所示!)。如果您想检查常见的数据类型类,这非常有帮助:

enter image description here

如您所见,np.str_np.unicode_ 都是“子类”np.character

关于python - 与 numpy 进行通用字符串比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45837456/

相关文章:

python - 创建与另一个相同大小的随机 numpy 矩阵。

python - ValueError:无法将字符串转换为 float :在 python 上绘制图形

python - 在 Linux shell 脚本中并行运行 python 命令

python - 将列表理解表达式拆分为多行以更好地了解发生了什么?

numpy - 根据范围内的值过滤numpy数组中的行

python-3.x - 如何查找另一列的不同行中具有多个值的列值的总长度

python - numpy.array2string 未检测 native 类型

python : How to return most occurrent value on each row depend on fix columns?

python - 在 svg 中设置默认单位(Python svgwrite)

python - 在Python中捕获警告并在捕获时运行bash脚本?