Search a Numpy Array for a value

In a Numpy array, we can search for a specific value using the numpy.where() method. This method returns the index where the specific element is found.

Let us see the following examples:

  1. Search a 1D NumPy array for a value
  2. Search a 2D NumPy array for a value
  3. Search a 3D NumPy array for a value

1. Search a 1D NumPy array for a value

# Search a 1d NumPy array for a value

import numpy as np

n = np.array([15, 20, 50, 70, 80, 87, 98, 120, 130])
print(n)

# search
res = np.where(n == 50)
print(res)

Output

[ 15  20  50  70  80  87  98 120 130]
(array([2]),)

2. Search a 2D NumPy array for a value

# Search a 2d NumPy array for a value

import numpy as np

# Create a 2d array
n = np.array([[1, 3, 5, 7],
              [4, 8, 12, 18],
              [25, 38, 82, 98]
              ])

# search
res = np.where(n == 82)
print(res)

Output

(array([2]), array([2]))

3. Search a 3D NumPy array for a value

# Search a 3d NumPy array for a value

import numpy as np

n = np.array([[
               [10, 20, 30],
               [40, 50, 60]],
              [
               [70, 80, 90],
               [100, 110, 120]]
             ])

# search
res = np.where(n == 60)
print(res)

Output

(array([0]), array([1]), array([2]))

If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others.

For Videos, Join Our YouTube Channel: Join Now


Read More:

Split Numpy Array
Sorting Numpy Arrays
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment