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 do I use the scipy ttest_ind function in Python?
- How to use Python, XML-RPC, and NumPy together?
- How can I use Python and Numpy to zip files?
- How can I use Python and Numpy to parse XML data?
- How do I install and use Python Scipy from PyPI?
- How do I calculate a Jacobian matrix using Python and NumPy?
- How can I use Python and SciPy to perform a hypothesis test?
- How can I use Python SciPy to fit a model?
- How do I create a numpy array of zeros using Python?
See more codes...