📜  numpy where - Python (1)

📅  最后修改于: 2023-12-03 15:33:14.288000             🧑  作者: Mango

NumPy: Where - Python

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.

Syntax

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.
Examples
Basic usage
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.]
Using conditions on matrices
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]]
Using where with no x or y arguments
import numpy as np

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

result = np.where(condition)
print(result)

Output:

(array([3, 4]),)
Conclusion

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.