Numpy where function: 4 Examples

Numpy has many inbuilt functions that makes mathematical calculations very easy. The numpy.where function is one of them. In this tutorial you will know how to implement this function with examples.

Syntax of the numpy where function

numpy.where(condition[, x, y])

Explanation of the parameters

  1. condition: It is a Boolean array or array of indices. It returns the indices in all the cases when the condition is true.
  2. x or y: This parameter is optional. It is used when the condition is true or false. If it is true then x will be used and if false y will be used.

Examples on Numpy where function

In NumPy, the numpy.where() function is used to return the indices of elements in an input array where a given condition is satisfied. It can be used in several ways, and I’ll provide examples for each.

Example 1 : Basic Usage of numpy where function

Here I will just create a sample numpy array and know the basic usage of the numpy.where() function.

import numpy as np

# Create an array
arr = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])

# Define a condition
condition = (arr % 2 == 0)

# Use np.where to get indices where the condition is True
indices = np.where(condition)

print("Indices of True elements:", indices)

Output

Indices of True elements: (array([0, 0, 0, 1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2, 0, 1, 2]))

Example 2: Get Values Where Condition is True

# Use np.where to get values where the condition is True
values = arr[np.where(condition)]

print("Values where the condition is True:", values)

Output

Values where the condition is True: [10 20 30 40 50 60 70 80 90]

Example 3: Replace Values Based on Condition

# Replace values based on the condition
arr[np.where(condition)] = 0

print("Modified array:", arr)

Output

Modified array: [[0 0 0]
 [0 0 0]
 [0 0 0]]

Example 4: Using np.where with Two Conditions

# Create two conditions
condition1 = (arr % 2 == 0)
condition2 = (arr > 4)

# Use np.where with two conditions
indices = np.where(np.logical_and(condition1, condition2))

print("Indices satisfying both conditions:", indices)

Output

Indices satisfying both conditions: (array([0, 0, 0, 1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2, 0, 1, 2]))

In the examples above, the conditions can be adjusted based on your specific use case.

Conclusion

The numpy where() function is the most often used function for manipulating the arrays based on conditions. The above examples covered the implementation of the np.where() function. You can use any examples based on the criteria while coding.

Hi, I am CodeTheBest. Here you will learn the best coding tutorials on the latest technologies like a flutter, react js, python, Julia, and many more in a single place.

SPECIAL OFFER!

This Offer is Limited! Grab your Discount!
15000 ChatGPT Prompts
Offer Expires In:
close-link