NumPy Where Function

In this tutorial you will learn:

  • What is array search?
  • NumPy where() function
  • Python Syntax

Array Search

Array search is carried out to check whether a specific element (alphabet / word / number) exist in an array or not. Generally all the searching algorithms return index of the number being searched and procedure involves iterating through each element of the array. There are two methods in NumPy for searching the array

  • NumPy where() function
  • NumPy searchsorted() function

NumPy where() function

NumPy where() function is a built in function of NumPy array and it iterates through the complete array and return the index(es) where the required element being searched is found.

In this example we will search a 1D array using where() function, where() function will return the index at which the required element is found.

  1. import numpy as np
  2. my_arr = np.array([8,9,10,11,11,12,13,11])
  3. print('Array being searched is:', my_arr)
  4. #applying search algorithm
  5. res = np.where(my_arr == 11)
  6. print('\n The indexes at which we have successfully found the desired number:',res)

Lets take another example, in this example I am searching a character. Here you can observe that where() function works irrespective of the DataType of array.

  1. import numpy as np
  2. my_arr = np.array(['a','b','c','c','d'])
  3. print('Array being searched is:', my_arr)
  4. #applying search algorithm
  5. res = np.where(my_arr == 'c')
  6. print('\n The indexes at which we have successfully found the desired character:',res)

In this example we are finding the indexes of the elements having value less than the 10.

  1. import numpy as np
  2. my_arr = np.array([6,7,8,9,10,11,12,13])
  3. print('Array being searched is:', my_arr)
  4. #applying search algorithm
  5. res = np.where(my_arr < 10)
  6. print('\n The indexes at which we have successfully found the desired number:',res)

Using where() function we can also find the indexes of odd and even numbers. Lets take an example, in this example we will displaying all the indexes of even and odd elements of the array separately.

  1. import numpy as np
  2. my_arr = np.array([1,2,3,4,5,6,7,8,9,10])
  3. print('Array being searched is:', my_arr)
  4. #applying search algorithm on even numbers
  5. res1 = np.where(my_arr%2 == 0)
  6. #applying search algorithm on odd numbers
  7. res2 = np.where(my_arr%2 == 1)
  8. print('\n The indexes at which we have successfully found the even numbers:\n',res1)
  9. print('\n The indexes at which we have successfully found the odd numbers:',res2)

Add new comment