Introduction to Python NumPy Searching Arrays
Python NumPy Searching Arrays
You can perform various operations to search for specific elements or conditions within arrays.
Here are some common functions for searching arrays:
Using np.where()
The np.where()
function returns the indices of elements in an array that satisfy a given condition.
It takes a condition as an argument and returns an array of indices where the condition is true.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Find the indices where the elements are greater than 3
indices = np.where(arr > 3)
print(indices)
Output:
(array([3, 4]),)
Using np.argmax()
and np.argmin()
The np.argmax()
function returns the index of the maximum value in an array, while np.argmin()
returns the index of the minimum value.
import numpy as np
arr = np.array([1, 4, 2, 7, 5])
# Find the index of the maximum value
max_index = np.argmax(arr)
print(max_index)
# Find the index of the minimum value
min_index = np.argmin(arr)
print(min_index)
Output:
3
0
Using np.nonzero()
The np.nonzero()
function returns the indices of non-zero elements in an array.
import numpy as np
arr = np.array([0, 1, 0, 3, 0, 5])
# Find the indices of non-zero elements
indices = np.nonzero(arr)
print(indices)
Output:
(array([1, 3, 5]),)
Using np.extract()
The np.extract()
function returns elements from an array that satisfy a given condition.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Extract elements greater than 3
result = np.extract(arr > 3, arr)
print(result)
Output:
[4 5]