NumPy where() Function With Examples

  • Post author:
  • Post category:NumPy / Python
  • Post last modified:January 20, 2023

Python NumPy where() function is used to return the indices of elements in an input array where the given condition is satisfied. Use this function to select elements from two different sequences based on a condition on a different NumPy array. If we are passing all 3 arguments to numpy.where(). Then all the 3 numpy arrays must be of the same length otherwise it will raise the Value Error.

In this article, I will explain Python NumPy where() function using its syntax, parameters, and how to use it to check the conditions on an array and get an array based on conditions on another array.

1. Quick Examples of Python NumPy where Function

If you are in a hurry, below are some quick examples of how to use Python NumPy where() function.


# Below are the quick examples

# Example 1: Use numpy.where() with 1 Dimensional Arrays
arr1 = np.where(arr > 17)

# Example 2: Get the specified resultant array
arr2 = np.where(arr > 17, 1, 3)

# Example 3: Get some of resultant array as it is
arr2 = np.where(arr > 17, 5, arr)

# Example 4: Use numpy.where() function
arr2 = np.where(arr <17, -1, 100)

# Example 5: Ndarray without using np.where()
arr = np.array([[12,14,17,19],[13,16,24,27]])
arr2 = arr < 17

# Example 6: Use numpy.where() to multiple conditions
arr2 = np.where((arr > 14) & (arr < 24), -2, 150)

# Example 7: Use bool value 
arr2 = (arr > 14) & (arr < 24)

2. Syntax of NumPy where()

Following is the syntax of NumPy where() function.


# Syntax of where()
numpy.where(condition, [x, y, ])

2.1 Parameters of the where()

Following are the parameters of the NumPy where()

  • 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.

2.2 Return Value of the where()

  • It returns an array if both x and y are specified, the output array contains elements of x where the condition is True and elements of y where the condition is false.
  • It returns a tuple of indices if an only condition is given, the indices where the condition is True.

3. Usage of NumPy where() Function

Python NumPy where() is used to create a new array from the existing array based on conditions. It returns the indices of the array for which each condition is True.

3.1 Use NumPy where() with Single Condition

Using where() function we can convert one array to another array based on some condition. Let’s create NumPy array using numpy.array() function.


import numpy as np

# Create a numpy array
arr = np.array([[12,14,17,19,24,27,35,38]])

# Use numpy.where() with 1 Dimensional Arrays
arr1 = np.where(arr > 17)
print(arr1)

# Output:
# (array([0, 0, 0, 0, 0], dtype=int64), array([3, 4, 5, 6, 7], dtype=int64))

Here, you can observe tuple has been returned. As I mentioned above that when passed only condition into the where() it will return a tuple of indices.

You can use the same conditional expression (arr > 17) but specify that the result array should have a value of 1 where the condition true and a value of 3 where the condition is false. The result is an array with a value of 3 where arr is less than 17 and a value of 1 otherwise.


# Get the specified resultant array
arr2 = np.where(arr > 17, 1, 3)
print(arr2)

# Output:
# [[3 3 3 1 1 1 1 1]]

In order to create an array to another array using np.where(arr > 17,5,arr) to keep the value in the original array for one of the results. Here, You keep the value arr if the condition resolves to false.


# Get some of resultant array as it is
arr2 = np.where(arr > 17, 5, arr)
print(arr2)

# Output:
[12 14 17  5  5  5  5  5]]

4. Use where() Function With 2- D Array

numpy.where() function returns ndarray which is x if the condition is True and y if False. x, y, and condition need to be broadcastable to the same shape.


import numpy as np
 
# Create a numpy array
arr = np.array([[12,14,17,19],[13,16,24,27]])

# Use numpy.where() function
arr2 = np.where(arr <17, -1, 100)
print(arr2)

# Output:
# [[ -1  -1 100 100]
# [ -1  -1 100 100]]

Alternatively, we can return a boolean values of ndarray can be obtained by a conditional expression including ndarray without using np.where().


# Ndarray without using np.where()
arr = np.array([[12,14,17,19],[13,16,24,27]])
arr2 = arr < 17
print(arr2)

# Output:
# [[ True  True False False]
# [ True  True False False]]

5. Use NumPy where() without condition expression

In all the previous examples we passed a condition expression as the first argument, which will be evaluated to a bool array. But we can pass a bool array too instead of that,

numpy.where() iterates over the bool array, and for every True, it yields the corresponding element array x, and for every False, it yields the corresponding element from the array y. So, it returns an array of items from x where the condition is True and elements from y elsewhere.


import numpy as np

# Use numpy.where() without condition
arr2 = np.where([True, False, True], [12,14,17], [13,16,24])
print(arr2)

# Output:
# [12 16 17]

6. Use numpy.where() with Multiple Conditions

You can use numpy.where() with multiple conditions, where each conditional expression is enclosed in () and & or | is used, the processing is applied to multiple conditions.


# Use numpy.where() to multiple conditions
arr2 = np.where((arr > 14) & (arr < 24), -2, 150)
print(arr2)

# Output:
# [[150 150  -2  -2]
#  [150  -2 150 150]]

Get boolean value ndarray that can be obtained by multiple conditional expressions including ndarray without using np.where().


# Use bool value 
arr2 = (arr > 14) & (arr < 24)
print(arr2)

# Output:
# [[False False  True  True]
# [False  True False False]]

7. Conclusion

In this article, I have explained how to use Python numpy.where() function how to get element indices from the array when condition meets. Also learned to use both single arguments as well as multiple arguments with this function.

Happy Learning!!

References

Malli

I am Mallikarjuna an experienced technical writer with a passion for translating complex Python concepts into clear, concise, and user-friendly documentation. Over the years, I have written hundreds of articles in Pandas, NumPy, Python, and I take pride in my ability to bridge the gap between technical experts and end-users by delivering well-structured, accessible, and informative content.

Leave a Reply

You are currently viewing NumPy where() Function With Examples