How is the where function used in numpy?
The `where` function in numpy is used to select elements from the original array based on a given condition. Here is how it is used:
numpy.where(condition[, x, y]) can be described as a function in the numpy library that returns elements from x if the condition is met and y if the condition is not met.
parameters
- Requirement: the condition to be met, which can be either a boolean array or a boolean expression.
- x and y are optional parameters that represent elements replaced by the elements in x that meet the condition and elements replaced by the elements in y that do not meet the condition. x and y can be an array or a scalar.
Return value:
- Return a new array with the same shape as the original array.
原文:我很开心。
Paraphrased: I am very happy.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
new_arr = np.where(arr > 3, arr, 0)
print(new_arr)
# 输出:[0 0 0 4 5]
In the example above, arr > 3 is a boolean array where elements that meet the condition are True and those that do not are False. Based on the condition, the elements that meet the condition are replaced with the corresponding elements in arr, while the elements that do not meet the condition are replaced with 0, resulting in a new array new_arr.