Check if a NumPy Array contains a specific string

This tutorial will discuss about unique ways to check if a NumPy Array contains a specific string in Python.

Table Of Contents

Technique 1: Using “in” Keyword

Python provides an “in” keyword to check if a NumPy contains a value or not. Suppose we have a NumPy Array of strings and an individual string value,

import numpy as np

# A NumPy Array of strings
arr = np.array(['Why', 'This', 'That', 'How', 'Where'])

value = 'How'

Now we want to check if the string value “How” exists in this NumPy array or not. For that we can apply the “in” keyword. Like this,

value in arr

It will return True if the given string “value” exists in the given NumPy array “arr”.

Let’s see the complete example,

import numpy as np

# A NumPy Array of strings
arr = np.array(['Why', 'This', 'That', 'How', 'Where'])

value = 'How'

# Check if numpy array contains the string
if value in arr:
    print(f"Yes, NumPy Array contains the string")
else:
    print(f"No, NumPy Array does not contain the string")

Output

Yes, NumPy Array contains the string

Technique 2: Using numpy.where()

To check if a NumPy Array contains a specific string value, we can use the numpy.where() method. Compare the NumPy Array with the given value, and it will return a boolean array. Pass that boolean array to numpy.where() method. It will return a tuple containing two values. Where first value is an array of indices. These indices are the position of elements with True value in the boolean array. So, if the size of first value in returned tuple is more than 0, then it means the given string exists in the NumPy Array.

Let’s see the complete example,

import numpy as np

# A NumPy Array of strings
arr = np.array(['Why', 'This', 'That', 'How', 'Where'])

value = 'How'

# Check if numpy array contains the string
index = np.where(arr == value)

if index[0].size > 0:
    print(f"Yes, NumPy Array contains the string")
else:
    print(f"No, NumPy Array does not contain the string")

Output

Yes, NumPy Array contains the string

Summary

We learned about two different ways to check if a string exists in a NumPy Array. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top