23

How can I determine if a Numpy array contains a string? The array a in

a = np.array('hi world')

has data type dtype('|S8'), where 8 refers to the number of characters in the string.

I don't see how regular expressions (such as re.match('\|S\d+', a.dtype)) would work here as the data type isn't simply '|S8'.

1 Answer 1

25
a.dtype.char == 'S'

or

a.dtype.type is np.string_

for Python 3.x you'll need

a.dtype.type is np.str_

See NumPy docs, Data type objects, Attributes.

Sign up to request clarification or add additional context in comments.

6 Comments

I noticed there's also a.dtype.kind == 'S'. Sweet!
Just a note: seems that this needs to be a.dtype.type is np.str_ in Python 3.x
For Python 2.x and 3.x you could test against a.dtype.kind in {'U', 'S'} to catch strings and unicode.
What happens if you put strings in an object array with character 'O'?
a.dtype.type is np.string_ or a.dtype.type is np.str_ is a further alternative
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.