python-scipyHow can I use the "where" function in Python Numpy?
The where function in Python Numpy can be used to return elements from an array based on a condition. It can be used in two different ways:
- np.where(condition, x, y): returns elements from x if the condition is true, and elements from y if the condition is false.
Example
import numpy as np
array_1 = np.array([1, 2, 3, 4, 5])
array_2 = np.array([10, 20, 30, 40, 50])
# Return elements from array_1 if the element is greater than 3, else return elements from array_2
result = np.where(array_1 > 3, array_1, array_2)
print(result)Output example
[10 20 30  4  5]
- np.where(condition): returns the indices of elements that satisfy the condition.
Example
import numpy as np
array_1 = np.array([1, 2, 3, 4, 5])
# Return the indices of elements that are greater than 3
result = np.where(array_1 > 3)
print(result)Output example
(array([3, 4]),)
Helpful links
More of Python Scipy
- How do I create a 2D array of zeros using Python and NumPy?
- How can I use Python and SciPy to find the zeros of a function?
- How can I check if a certain version of Python is compatible with SciPy?
- How do I use Scipy zeros in Python?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- How do I use the NumPy transpose function in Python?
- How can I use Python and Numpy to parse XML data?
- How do I calculate the cross-correlation of two arrays using Python and NumPy?
- How can I use Python and Numpy to zip files?
- How do I download a Python Scipy .whl file?
See more codes...