np.where is a function from the NumPy library, which is a powerful library for numerical computations in Python. The np.where function is often used for conditional selection and the manipulation of NumPy arrays, and it can serve multiple purposes.
Here's a brief overview of how np.where can be used:
Conditional Selection
To select elements from an array based on a condition, np.where can be used in the following form:
import numpy as np
array = np.array([1, 2, 3, 4, 5])
condition = array > 3
new_array = np.where(condition, array, 0) # Replaces with 0 where condition is False
Here, new_array would be [0, 0, 0, 4, 5], since only 4 and 5 satisfy the condition array > 3.
The np.where function takes three arguments here:
The condition (array > 3),
The value to use when the condition is True (original array),
The value to use when the condition is False (0).
Finding Indices
Another common usage of np.where is finding the indices of elements that satisfy a certain condition. For instance:
indices = np.where(array > 3)
The variable indices would now hold the indices in the array where the elements are greater than 3.
Combining Conditions
You can also combine multiple conditions using the logical operators such as & (and), | (or), ~ (not):
Here, indices might look like (array([1, 1]), array([0, 1])), meaning that the elements satisfying the condition are located at (1, 0) and (1, 1) in the array.
Remember to import NumPy using import numpy as np at the beginning of your script or notebook to access np.where and other NumPy functions.