numpy.find() in Python


There is no numpy.find() function in NumPy. However, there are several functions that can be used to find elements in a NumPy array.

  • numpy.where(): This function returns the indices of elements in an array that satisfy a given condition. For example:
import numpy as np

arr = np.array([1, 2, 3, 4, 5])
indices = np.where(arr > 3)
print(indices)

Output:

(array([3, 4]),)
  • numpy.argwhere(): This function is similar to numpy.where(), but it returns the indices of elements that are non-zero. For example:
import numpy as np

arr = np.array([0, 1, 0, 2, 3])
indices = np.argwhere(arr)
print(indices)

Output:

array([[1],
       [3],
       [4]])
  • numpy.nonzero(): This function returns the indices of elements that are non-zero. It is similar to numpy.argwhere(), but it returns a tuple of arrays, one for each dimension of the input array. For example:
import numpy as np

arr = np.array([[0, 1, 0], [2, 0, 3]])
indices = np.nonzero(arr)
print(indices)

Output:

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

This means that the non-zero elements of arr are at positions (0, 1), (1, 0), and (1, 2).

  • numpy.searchsorted(): This function finds the indices where elements should be inserted to maintain order in a sorted array. For example:
import numpy as np

arr = np.array([1, 3, 5, 7])
indices = np.searchsorted(arr, [2, 4, 6])
print(indices)

Output:

array([1, 2, 3])

This means that the elements [2, 4, 6] should be inserted at positions 1, 2, and 3 in the sorted array arr.

Note: If you meant numpy.ndarray.find() instead of numpy.find(), then it is worth noting that there is no such method in NumPy arrays.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.