Open In App

How to check whether specified values are present in NumPy array?

Last Updated : 22 Sep, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes we need to test whether certain values are present in an array. Using Numpy array, we can easily find whether specific values are present or not. For this purpose, we use the “in” operator. “in” operator is used to check whether certain element and values are present in a given sequence and hence return Boolean values ‘True” and “False“.

Example 1:

Python3




# importing Numpy package
import numpy as np
  
# creating a Numpy array
n_array = np.array([[2, 3, 0],
                    [4, 1, 6]])
  
print("Given array:")
print(n_array)
  
# Checking whether specific values
# are present in "n_array" or not
print(2 in n_array)
print(0 in n_array)
print(6 in n_array)
print(50 in n_array)
print(10 in n_array)


Output:

Given array:
[[2 3 0]
[4 1 6]]
True
True
True
False
False

In the above example, we check whether values 2, 0, 6, 50, 10 are present in Numpy array ‘n_array‘ using the ‘in‘ operator.

Example 2: 

Python3




# importing Numpy package
import numpy as np
  
# creating a Numpy array
n_array = np.array([[2.14, 3, 0.5],
                    [4.5, 1.2, 6.2],
                    [20.2, 5.9, 8.8]])
  
print("Given array:")
print(n_array)
  
# Checking whether specific values
# are present in "n_array" or not
print(2.14 in n_array)
print(5.28 in n_array)
print(6.2 in n_array)
print(5.9 in n_array)
print(8.5 in n_array)


Output:

Given array:
[[ 2.14  3.    0.5 ]
[ 4.5   1.2   6.2 ]
[20.2   5.9   8.8 ]]
True
False
True
True
False

In the above example, we check whether values 2.14, 5.28, 6.2, 5.9, 8.5 are present in Numpy array ‘n_array‘.

Example 3:

Python3




# importing Numpy package
import numpy as np
  
# creating a Numpy array
n_array = np.array([[4, 5.5, 7, 6.9, 10],
                    [7.1, 5.3, 40, 8.8, 1],
                    [4.4, 9.3, 6, 2.2, 11],
                    [7.1, 4, 5, 9, 10.5]])
  
  
print("Given array:")
print(n_array)
  
# Checking whether specific values
# are present in "n_array" or not
print(2.14 in n_array)
print(5.28 in n_array)
print(8.5 in n_array)


Output:

Given array:
[[ 4.   5.5  7.   6.9 10. ]
[ 7.1  5.3 40.   8.8  1. ]
[ 4.4  9.3  6.   2.2 11. ]
[ 7.1  4.   5.   9.  10.5]]
False
False
False

In the above example, we check whether values 2.14, 5.28, 8.5 are present in Numpy array ‘n_array‘.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads