numpy
  1. numpy-numpywhere

NumPy Where()

NumPy is a powerful Python package that provides fast numerical computing capabilities. The numpy.where() function is used to return an array of elements depending on whether a condition is true or false.

Syntax

The basic syntax for using numpy.where() function is:

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

Here, the condition is a Boolean array that contains the conditions to be checked. If the condition is true, the corresponding element is taken from x, otherwise, it is taken from y. If x and y are not specified, the function returns a tuple of ndarray with indices where the condition is true.

Example

Consider the following example where we will use numpy.where() function to return elements based on a condition:

import numpy as np

x = np.array([1, 2, 3, 4, 5])
y = np.array([6, 7, 8, 9, 10])

result = np.where(x < 3, x, y)
print(result)

Output:

[1 2 8 9 10]

In this example, we compared the values of x with 3. If the value of x is less than 3, we take that element from x. Otherwise, we take that element from y.

Explanation

The numpy.where() function is used to return an array of elements based on a condition. The condition parameter is a Boolean array that contains the conditions to be checked. If the condition is true, the corresponding element is taken from x, otherwise, it is taken from y. If x and y are not specified, the function returns a tuple of ndarray with indices where the condition is true.

Use

The numpy.where() function is used to filter ndarray based on a condition. It can be used to replace specific values in an array, replace missing values or NaNs, and to do other complex operations.

Important Points

  • The condition is a Boolean array. If the condition is true, the corresponding element is taken from x, otherwise, it is taken from y.
  • The x and y parameters are optional. If they are not specified, numpy.where() function returns a tuple of ndarray with the indices where the given condition is true.
  • numpy.where() function can be used with other NumPy functions such as np.logical_and(), np.logical_or(), and np.logical_not().

Summary

The numpy.where() function is used to return an array with elements based on a condition. It is used to filter ndarray based on a condition. If the condition is true, the corresponding element is taken from x, otherwise, it is taken from y. If x and y are not specified, the function returns a tuple of ndarray with indices where the condition is true.

Published on: