NumPy where

  • Post category:NumPy

In this NumPy tutorial, you’ll learn how to use the NumPy where function in Python.

# import numpy module
import numpy as np

# create a numpy array
var = np.array([11, 22, 33, 44, 55])

# print the array
print(var)

# print the index of the array where var greater than 30
print(np.where(var > 30))

# print the index of the array where var less than 30
print(np.where(var < 30))

# print the index of the array where var greater than or equal to 30
print(np.where(var >= 30))

# print the index of the array where var less than or equal to 30
print(np.where(var <= 30))

# print the index of the array where var equal to 30
print(np.where(var == 30))

# print the index of the array where var not equal to 30
print(np.where(var != 30))

Output:

[11 22 33 44 55]
(array([2, 3, 4], dtype=int64),)
(array([0, 1], dtype=int64),)
(array([2, 3, 4], dtype=int64),)
(array([0, 1], dtype=int64),)
(array([], dtype=int64),)
(array([0, 1, 2, 3, 4], dtype=int64),)

Free resources to learn advanced skills: AiHints and CodeAllow