str dtype的规范检测方式?

问题描述 投票:0回答:1

推荐用什么方法来检查str (U...)dtype? 我想我可以做 dtype.char == "U" 但这感觉有点黑客化。

一些 dtypes 可以直接与它们的Python等价物进行比较,例如

np.dtype("f8") == float
# True

str 可以用来创建一个 U... 数组,例如

 np.arange(4).astype(str)
 # array(['0', '1', '2', '3'], dtype='<U21')

但是

 np.arange(4).astype(str).dtype == str
 # False

:-(

python numpy typechecking
1个回答
1
投票

我想 np.issubdtype() 应该是你要找的。

>>> s = np.arange(4).astype(str)
>>> s
array(['0', '1', '2', '3'], 
      dtype='<U24')
>>> np.issubdtype(s.dtype, str)
True
© www.soinside.com 2019 - 2024. All rights reserved.