NumPy where() with multiple conditions in Python
In this tutorial, we learn how to use the numpy where() method in Python.
NumPy where() in Python:
Topics covered in this tutorial are,
- Syntax of numpy.where()
- Using numpy.where() with single condition
- Using numpy.where() with multiple conditions
Syntax of numpy.where() :
numpy.where(condition[, x, y])
Where x and y are two arrays. When the condition is true then the element in x must be considered and when the condition is false then the element in y must be considered.
NOTE: x and y are should of the same size.
Using numpy.where() with single condition:
import numpy as np arr = np.array([1,2,3,4]) np.where(arr>2,["High","High","High","High"],["Low","Low","Low","Low"])
array(['Low', 'Low', 'High', 'High'], dtype='<U4')
Here, we considered arr>2 as the condition. As 1 and 2 are not greater than 2, elements in the right array are considered. As 3 and 4 are greater than 2, elements in the left array are considered. Finally, we got output as [‘Low’, ‘Low’, ‘High’, ‘High’].
Using numpy.where() with Multi conditions:
import numpy as np arr = np.array([1,2,3,4,5,6,7,8]) np.where((arr>4) & (arr<8), ['X','X','X','X','X','X','X','X'],['Y','Y','Y','Y','Y','Y','Y','Y',])
array(['Y', 'Y', 'Y', 'Y', 'X', 'X', 'X', 'Y'], dtype='<U1')
Here, we considered (arr>4) & (arr<8) as the condition. As elements 1,2,3,4,8 don’t follow the condition, elements in the right array are considered. As 5,6 and 7 follow the condition, elements in the left array are considered. Finally, we got output as [‘Y’, ‘Y’, ‘Y’, ‘Y’, ‘X’, ‘X’, ‘X’, ‘Y’].
In this way numpy.where() method is useful to generate new arrays based on multiple conditions. I hope it might be helpful for you. Thank you!
Leave a Reply