NumPy where() Multiple Conditions

  • Post author:
  • Post category:NumPy / Python
  • Post last modified:November 10, 2023
  • Reading time:16 mins read

In NumPy, you can use the where() function to apply multiple conditions and return values based on those conditions. You can specify multiple conditions using logical operators like & (and), | (or), and ~ (not). The numpy.where() is a versatile function that can be used to create new arrays or update existing arrays based on specified conditions. In this article, I will explain how to use the where() function with multiple conditions with examples.

1. Quick Examples of Using where() with Multiple Conditions

If you are in a hurry, below are some quick examples of how to use multiple conditions in where() condition.


# Quick examples of where() with multiple conditions

# Example 1: Get the indices of array elements
arr1=np.where(arr)

# Example 2: Use numpy.where() multiple conditions
# With the & operator
arr2 = arr[np.where((arr >5) & (arr <25))]

# Example 3: Multiple conditions using | operator
# Use numpy.where() function
arr2 = arr[np.where((arr >5) | (arr % 2 == 0))]

# Example 4: Find number of values meet in a condition
arr2 = (arr[np.where((arr >5) | (arr % 2 == 0))]).size

# Example 5: Use numpy.where() multiple conditions 
# Using numpy.logical_and() function
arr2 = arr[np.where(np.logical_and(arr >5, arr <25))]

# Example 6: Use numpy.where() multiple conditions 
# Using logical_or() function
arr2 = arr[np.where(np.logical_or(arr >5, arr % 2 == 0))]

2. Usage of NumPy where()

First, let’s quickly see how to use a where() function, and later I will cover examples of how to use it with multiple conditions. When we pass the NumPy array to the numpy.where() it will return the indices of NumPy array elements. Let’s create a NumPy array using numpy.array().


# Import numpy
import numpy as np

arr = np.array([5, 10, 15, 20, 25])
print("Given array:", arr)

# Get the indices of array elements
arr1=np.where(arr)
print("Get indices of given array:", arr1)

Yields below output.

numpy where multiple conditions

3. NumPy where() Multiple Conditions With the & Operator

To select the NumPy array elements from the existing array based on multiple conditions use the & operator along with the where() function. You can specify multiple conditions inside the where() function by enclosing each condition inside a pair of parenthesis and using an & operator.

Let’s pass the multiple conditions with the help of the & operator to the where() function and get the selected elements of the given NumPy array. For example,


import numpy as np

# Create a numpy array 
arr = np.array([5, 10, 15, 20, 25])

# Use numpy.where() multiple conditions with the & operator
arr2 = arr[np.where((arr >5) & (arr <25))]
print("Get selected array elements:", arr2)

Yields below output.

numpy where multiple conditions

4. Use where() Multiple Conditions With the | Operator

You can use the np.where() function with multiple conditions to modify the existing array based on those conditions.

In the below example, you can use the | (bitwise OR) operator to filter elements from a NumPy array. First condition1 checks if the elements arr are greater than 5, and condition2 checks if the elements are divisible by 2. The | operator is used to combine these conditions. This function returns the indices where either condition1 or condition2 is true. Finally, the elements corresponding to the selected indices are extracted from the original array arr and stored in the arr2 array.


import numpy as np

# Create a numpy array 
arr = np.array([5, 10, 15, 20, 25])

# Multiple conditions using | operator
# Use numpy.where() function
arr2 = arr[np.where((arr >5) | (arr % 2 == 0))]
print("Get selected array elements:\n", arr2)

# Output:
# Get selected array elements:
#  [10 15 20 25]

You can also use the size function to simply find how many values meet one of the conditions using (arr[np.where()]).size function. For instance, to create a NumPy array called arr with values [5, 10, 15, 20, 25] and then filters the array based on a condition using boolean indexing. Specifically, it selects elements arr that are greater than 5 or divisible by 2.

The condition arr > 5 checks for elements greater than 5, and arr % 2 == 0 checks for elements divisible by 2. The | operator represents logical OR, so it selects elements that satisfy either of these conditions.


import numpy as np

# Create a numpy array 
arr = np.array([5, 10, 15, 20, 25])

# Find number of values meet in a condition
arr2 = (arr[np.where((arr >5) | (arr % 2 == 0))]).size
print("Get selected array element:", arr2)

# Output:
# Get selected array element: 4

5. Use where() Multiple Conditions With the logical_and()

numpy.logical_and() function is used to calculate the element-wise truth value of AND gate in Python. Using this function inside the where() function to specify multiple conditions and get the selected elements from an existing array.

In this example, np.logical_and(arr > 5, arr < 25) creates a boolean array with True where both conditions are satisfied and False otherwise. np.where() then finds the indices where the conditions are True, and finally, these indices are used to extract the corresponding elements from the original array.


import numpy as np

# Create a numpy array 
arr = np.array([5, 10, 15, 20, 25])

# Use numpy.where() multiple conditions 
# Using numpy.logical_and() function
arr2 = arr[np.where(np.logical_and(arr >5, arr <25))]
print("Get selected array element:", arr2)

# Output:
# Get selected array element: [10 15 20]

6. Use where() Multiple Conditions With the logical_or()

You can use np.where() with np.logical_or() to filter elements based on multiple conditions using logical OR. For instance, np.logical_or(arr > 5, arr % 2 == 0) creates a boolean array with True where either condition (greater than 5 or divisible by 2) is satisfied and False otherwise. np.where() then finds the indices where the conditions are True, and these indices are used to extract the corresponding elements from the original array.


import numpy as np

# Create a numpy array 
arr = np.array([5, 10, 15, 20, 25])

# Use numpy.where() multiple conditions with the .logical_or()
arr2 = arr[np.where(np.logical_or(arr >5, arr % 2 == 0))]
print("Get selected array element:", arr2)

# Output:
# Get selected array element: [ 10 15 20 25]

Frequently Asked Questions NumPy where() Multiple Conditions

How can I use multiple conditions with the numpy.where() function?

You can use multiple conditions with the numpy.where() function by combining the conditions using logical operators such as & (and), | (or), and ~ (not). For instance, if you want to find the indices where both condition A and condition B are true, you can use numpy.where((condition_A) & (condition_B)).

Can I apply different operations based on different conditions using numpy.where()?

You can apply different operations based on different conditions using the numpy.where() function. Use the conditions to create a mask and then use the mask in the numpy.where() function to perform different operations accordingly.

Can I use numpy.where() in a NumPy ufunc (universal function)?

You can use numpy.where() inside a NumPy universal function (ufunc). A universal function is a function that operates element-wise on arrays. You can create your own ufunc using numpy.frompyfunc() or numpy.vectorize(), and within this function, you can use numpy.where() it for element-wise conditional operations.

How can I use numpy.where() with an “else” condition?

The numpy.where() doesn’t have a direct “else” clause. It operates based on a given condition and returns elements from one of the two arrays based on whether the condition is True or False. However, you can achieve similar functionality using numpy.where() in combination with basic arithmetic and logical operations.

Is it possible to use a mix of scalar values and arrays as conditions in numpy.where()?

You can use a mix of scalar values and arrays as conditions in numpy.where(). Scalar values will be broadcasted to match the shape of the arrays if necessary, and element-wise operations will be performed. This flexibility allows you to combine scalars and arrays to create complex conditions.

Conclusion

In this article, I have explained how to use multiple conditions on NumPy where() function by using the &(and), |(or), logical_and() and, logical_or() functions with examples.

Happy Learning!!

References

Vijetha

Vijetha is an experienced technical writer with a strong command of various programming languages. She has had the opportunity to work extensively with a diverse range of technologies, including Python, Pandas, NumPy, and R. Throughout her career, Vijetha has consistently exhibited a remarkable ability to comprehend intricate technical details and adeptly translate them into accessible and understandable materials. Follow me at Linkedin.

Leave a Reply