NumPy where() Method Example | How to Use NumPy where() Function in Python

Numpy where() method returns elements chosen from x or y depending on condition. If you want to select the elements based on condition, then we can use np where function. Using where() method, elements of the  Numpy array ndarray that satisfy the conditions can be replaced or performed specified processing.

You have toinstall numpy for this tutorial. Also, check your numpy version as well.

Syntax

numpy.where(condition, x, y)

where() Arguments

The where() method takes three arguments:

  • condition - a boolean or an array
  • x - value to take if the condition is True
  • y - value to take if the condition is False

Return Value

The where() method returns a new NumPy array.

Example 1: numpy.where() With Two Arrays

import numpy as np

x = np.array([1, 2, 3, 4])
y = np.array([10, 20, 30, 40])

test_condition = x < 3 

# if test_condition is True, select element of x
# if test_condition is False, select element of y
result = np.where(test_condition, x, y)

print(result)

Output

[1 2 30 40]

Example 2: numpy.where() with Operation

We can also use numpy.where() to perform operations on array elements.

import numpy as np

x = np.array([-1, 2, -3, 4])

# test condition
test_condition = x > 0

# if test_condition is True, select element of x
# if test_condition is False, select  x * -1
result = np.where(test_condition, x, x * -1)

print(result)

Output

[1 2 3 4]

Example 3: where() with Array Condition

We can use array_like objects (such as lists, arrays etc.) as a condition in the where() method.

import numpy as np

x = np.array([[1, 2], [3, 4]])
y = np.array([[-1, -2], [-3, -4]])

# returns element of x when True 
# returns element of y when False
result = np.where([[True, True], [False, False]], x, y)

print(result)

# returns element of x when True 
# returns element of y when False
result = np.where([[True, False], [False, True]], x, y)


print(result)

Output

[[1 2]
 [-3 -4]]

[[1 -2]
 [-3 4]]

Thanks for reading!!!

#numpy #python

NumPy where() Method Example | How to Use NumPy where() Function in Python
19.65 GEEK