How to use NumPy where() with multiple conditions in Python ?
In Python, NumPy has a number of library functions to create the array and where is one of them to create an array from the satisfied conditions of another array. The numpy.where() function returns the indices of elements in an input array where the given condition is satisfied.
numpy.where(condition[, x, y])
- condition : When True, yield x, otherwise yield y.
- x, y : Values from which to choose. x, y and condition need to be broadcastable to some shape.
Returns: [ndarray or tuple of ndarrays] If both x and y are specified, the output array contains elements of x where condition is True, and elements from y elsewhere.
If the only condition is given, return the tuple condition.nonzero(), the indices where the condition is True. In the above syntax, we can see the where() function can take two arguments in which one is mandatory and another one is optional. If the value of the condition is true an array will be created based on the indices.
Numpy where() with multiple conditions using logical OR.
Numpy where() with multiple conditions using logical AND.
Numpy where() with multiple conditions in multiple dimensional arrays.
The where() function in NumPy is used for creating a new array from the existing array with multiple numbers of conditions.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course