How to Check Whether Specified Values are Present in NumPy Array?
Given a NumPy array, the task is to check whether certain values exist inside it. For Example:
Input: arr = [ [2, 3, 0], Check: 2, 0, 6, 50, 10
[4, 1, 6] ]
Output: True, True, True, False, False
Let's explore different methods to do this task in Python.
Using NumPy's Vectorized Comparison
This method performs a direct element-wise comparison between the array and the given value. It works by generating a Boolean array showing where matches occur, and then verifying whether any match exists.
import numpy as np
arr = np.array([[2, 3, 0],
[4, 1, 6]])
v = 6
out = np.any(arr == v)
print(out)
Output
True
Explanation:
- "arr == v" creates a Boolean array where matching positions are True.
- np.any(...) checks if at least one match exists.
Using NumPy isin() for Multiple Values
This method checks whether one or more given values appear anywhere in the array by testing each value against all array elements and returning a Boolean result for each value.
import numpy as np
arr = np.array([[2, 3, 0],
[4, 1, 6]])
vals = [0, 50, 6]
out = {v: np.isin(v, arr) for v in vals}
print(out)
Output
{0: array(True), 50: array(False), 6: array(True)}
Explanation: np.isin(v, arr) returns True if value v appears anywhere in the array.
Using in Operator
This method checks membership by scanning the array element by element. NumPy internally allows the array to act as an iterable, enabling the use of the in operator to determine if a value exists.
import numpy as np
arr = np.array([[2, 3, 0],
[4, 1, 6]])
print(2 in arr)
print(10 in arr)
Output
True False
Explanation: 2 in arr scans array elements sequentially until a match is found.
Using Flattening and Python Membership
This method first converts the array into a 1-dimensional sequence and then checks whether the target value appears inside this flattened version.
import numpy as np
arr = np.array([[2, 3, 0],
[4, 1, 6]])
v = 3
out = v in arr.ravel()
print(out)
Output
True
Explanation:
- arr.ravel() converts the array into a 1D sequence.
- v in arr.ravel() performs linear search on the flattened data.