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 Python and SciPy to create a tutorial PDF?
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How do I use scipy.optimize.curve_fit in Python?
- How can I use Python and Numpy to parse XML data?
- How do I check the version of Python SciPy I'm using?
- How can I use Python and SciPy to generate a Voronoi diagram?
- How do I create a zero matrix using Python and Numpy?
See more codes...