📅  最后修改于: 2023-12-03 15:33:14.288000             🧑  作者: Mango
NumPy is a powerful library for numerical computing in Python, providing support for arrays and matrices, mathematical operations, and more. One useful function in NumPy is the where
function, which allows you to conditionally select elements from an array or matrix.
The syntax of the where
function is as follows:
numpy.where(condition[, x, y])
Where:
condition
: The condition that is tested for each element in the array/matrix. x
: The value(s) to be assigned to the output array/matrix where the condition is True. If x
is not provided, the function returns a tuple of arrays with indices where the condition is True.y
: The value(s) to be assigned to the output array/matrix where the condition is False. If y
is not provided, the function returns a tuple of arrays with indices where the condition is False.import numpy as np
arr = np.array([1, 2, 3, 4, 5])
condition = arr > 3
result = np.where(condition, arr, np.nan)
print(result)
Output:
[ nan nan nan 4. 5.]
import numpy as np
mat = np.array([[1, 2],
[3, 4],
[5, 6]])
condition = mat > 3
x = np.array([[0, 0],
[0, 0],
[0, 0]])
y = np.array([[1, 1],
[1, 1],
[1, 1]])
result = np.where(condition, x, y)
print(result)
Output:
[[1 1]
[1 1]
[0 0]]
where
with no x
or y
argumentsimport numpy as np
arr = np.array([1, 2, 3, 4, 5])
condition = arr > 3
result = np.where(condition)
print(result)
Output:
(array([3, 4]),)
NumPy's where
function is a powerful tool for selecting elements from arrays or matrices based on conditions. With its flexibility and ease of use, it can greatly simplify your data processing and analysis tasks.