Search code examples
pythonnumpytypechecking

Canonical way of testing for str dtype?


What is the recommended way of checking for str (U...) dtype? I suppose I could do dtype.char == "U" but that feels a bit hackish.

Some dtypes can be directly compared to their Python equivalent, for example

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

and str can be used to create a U... array, for example

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

But

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

:-(


Solution

  • I think np.issubdtype() should be what you are looking for:

    >>> s = np.arange(4).astype(str)
    >>> s
    array(['0', '1', '2', '3'], 
          dtype='<U24')
    >>> np.issubdtype(s.dtype, str)
    True