• Post author:
  • Post category:NumPy / Python
  • Post last modified:March 27, 2024
  • Reading time:18 mins read
You are currently viewing NumPy where() Function With Examples

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 three arguments to numpy.where(). Then all three NumPy arrays must be of the same length otherwise it will raise the Value Error.

Advertisements

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 the Python NumPy where() function.


# Quick examples of where() function

# Example 1: Use numpy.where() 
# With 1 Dimensional Arrays
arr = np.array([[12,14,17,19,24,27,35,38]])
arr2 = 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
arr = np.array([[12,14,17,19],[13,16,24,27]])
arr2 = np.where(arr <17, -1, 100)

# Example 5: Create a boolean array 
# Based on the condition
boolean_array = (arr < 17)

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

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

# Example 8: 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 only condition is given, the indices where the condition is True.

3. Usage of NumPy where() Function

The numpy.where() function in Python’s NumPy library is used to create a new array from an existing array based on specified conditions. It returns the indices of the elements in the original array for which the given 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
import numpy as np

# Create a numpy array
arr = np.array([[12,14,17,19,24,27,35,38]])
print("Given array:\n", arr)

# Use numpy.where() with 1 Dimensional Arrays
arr2 = np.where(arr > 17)
print("Create a new array from existing array:\n",arr2)

Yields below output.

numpy where function

Here, you can observe tuple has been returned. As I mentioned above 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("Create a new array from existing array:\n",arr2)

Yields below output.

numpy where function

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("Create a new array from existing array:\n",arr2)

# Output:
# Given array:
#  [[12 14 17 19 24 27 35 38]]
# Create a new array from existing array:
#  [[12 14 17  5  5  5  5  5]]

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

To use numpy.where() with a 2D array involves specifying conditions on the elements of the array, and then obtaining the indices or elements based on these conditions. 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.

In the below example, the condition arr < 17 checks elements in the original array that are less than 17. Where the condition is True, -1 is placed in the new array. Where the condition is False, 100 is placed in the new array. In the new array arr2, values less than 17 from the original array are replaced with -1, and values greater than or equal to 17 are replaced with 100.


import numpy as np
 
# Create a numpy array
arr = np.array([[12,14,17,19],[13,16,24,27]])
print("Given 2D array:\n", arr)

# Use numpy.where() function
arr2 = np.where(arr <17, -1, 100)
print("Create a new array from existing array:\n",arr2)

# Output:
# Given 2D array:
#  [[12 14 17 19]
#  [13 16 24 27]]
# Create a new array from existing array:
#  [[ -1  -1 100 100]
#  [ -1  -1 100 100]]

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

In the below example, the expression (arr < 17) is evaluated element-wise on the original array. The resulting boolean array contains True where the condition is satisfied (i.e., where the element is less than 17) and False where it is not.


import numpy as np
 
# Create a numpy array
arr = np.array([[12,14,17,19],[13,16,24,27]])
print("Given 2D array:\n", arr)

# Create a boolean array based on the condition
boolean_array = (arr < 17)
print("Boolean array based on the condition:\n", boolean_array)

# Output:
# Given 2D array:
#  [[12 14 17 19]
#  [13 16 24 27]]
# Create a new array from existing array:
#  [[ True  True False False]
#  [ True  True False False]]

5. Use NumPy where() without condition expression

In all the previous examples you passed a condition expression as the first argument, which will be evaluated to a bool array. But you 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("Create a new array without condition:\n",arr2)

# Output:
# Create a new array without condition:
#  [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.


import numpy as np

# Create a numpy array
arr = np.array([[12,14,17,19],[13,16,24,27]])
print("Given 2D array:\n", arr)

# Use numpy.where() to multiple conditions
arr2 = np.where((arr > 14) & (arr < 24), -2, 150)
print("Create a new array of multiple conditions:\n",arr2)

# Output:
# Given 2D array:
#  [[12 14 17 19]
#  [13 16 24 27]]
# Create a new array of multiple conditions:
#  [[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("Getting boolean array:\n",arr2)

# Output:
# Given 2D array:
#  [[12 14 17 19]
#  [13 16 24 27]]
# Getting boolean array:
#  [[False False  True  True]
#  [False  True False False]]

Frequently Asked Questions

What is the where() function in NumPy?

The numpy.where() function in NumPy is a versatile tool used for array manipulation. It is used to perform element-wise conditional operations on arrays. The function returns the indices of elements in an input array where a specified condition is satisfied.

What is the purpose of the numpy.where() function?

The numpy.where() function is used to perform element-wise conditional operations on arrays. It returns the indices of elements in an input array that satisfy a specified condition.

Is numpy.where() only limited to numerical data?

The numpy.where() function is not limited to numerical data. It can be applied to arrays of any data type, including numerical data, strings, or custom objects. The condition provided to numpy.where() can involve any valid expression that results in a boolean array.

Can the numpy.where() function modify the original array?

The numpy.where() function does not modify the original array. It returns a new array or a tuple of arrays containing the indices based on the specified condition. The original array remains unchanged.

Can numpy.where() be used with multi-dimensional arrays?

The numpy.where() function can be used with multi-dimensional arrays. It operates element-wise on the input arrays, making it suitable for both 1D and multi-dimensional arrays. When used with multi-dimensional arrays, numpy.where() returns a tuple of arrays, each representing the indices where the specified condition is true along a particular axis.

What is the performance impact of using numpy.where() on large arrays?

The performance impact depends on the complexity of the condition and the size of the input arrays. Generally, NumPy is optimized for array operations, so using numpy.where() on large arrays is efficient.

Conclusion

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

Happy Learning!!

References