This tutorial will discuss about unique ways to check if a value exists in a NumPy array in Python.
Table Of Contents
Technique 1: Using “in” keyword
Python provides an “in” keyword to check if a sequence contains a value or not. We can use that to check if a NumPy Array contains a value or not. Suppose we have a NumPy Array,
import numpy as np arr = np.array([34, 23, 45, 28, 90, 11, 34]) value = 90
Now we want to check if value “90” 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 value
exists in the given NumPy array “arr”.
Frequently Asked:
Let’s see the complete example,
import numpy as np # A NumPy Array arr = np.array([34, 23, 45, 28, 90, 11, 34]) value = 90 # Check if a value exists in numpy array if value in arr: print("Yes, value exists in the array") else: print("No, value does not exists in the array")
Output
Yes, value exists in the array
Technique 2: Using isin() and any() methods
The numpy.isin()
method excepts a NumPy array and a value as arguments, and returns a boolean array. Each True
value in the boolean array represents that the corresponding element in the given array matches with the given value. Then we can apply the numpy.any()
method on this boolean numpy array, to check if it contains any True
value. If Yes, then it means that the given value exists in the NumPy Array.
Let’s see the complete example,
Latest Python - Video Tutorial
import numpy as np # A NumPy Array arr = np.array([34, 23, 45, 28, 90, 11, 34]) value = 90 # Check if a value exists in numpy array if np.isin(value, arr).any(): print("Yes, value exists in the array") else: print("No, value does not exists in the array")
Output
Yes, value exists in the array
Summary
We learned about two different ways to check if a NumPy Array contains a given value or not in Python. Thanks.
Latest Video Tutorials