w3resource

Find and Index elements in 2D NumPy array using np.nonzero


Using np.nonzero for Indexing:

Write a NumPy program that creates a 2D NumPy array and uses np.nonzero to find indices of elements that satisfy a condition, then uses these indices for advanced indexing.

Sample Solution:

Python Code:

import numpy as np

# Create a 2D NumPy array of shape (5, 5) with random integers
array_2d = np.random.randint(0, 100, size=(5, 5))

# Define the condition to find elements greater than 50
condition = array_2d > 50

# Use np.nonzero to find indices of elements that satisfy the condition
indices = np.nonzero(condition)

# Use the indices for advanced indexing
selected_elements = array_2d[indices]

# Print the original array, the condition, indices, and the selected elements
print('Original 2D array:\n', array_2d)
print('Condition (elements > 50):\n', condition)
print('Indices of elements > 50:\n', indices)
print('Selected elements using advanced indexing:\n', selected_elements)

Output:

Original 2D array:
 [[23 75 88 60 91]
 [82 35 46 72 12]
 [51 94 30 82 66]
 [64 51 89 92 75]
 [27 15 74 63 83]]
Condition (elements > 50):
 [[False  True  True  True  True]
 [ True False False  True False]
 [ True  True False  True  True]
 [ True  True  True  True  True]
 [False False  True  True  True]]
Indices of elements > 50:
 (array([0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4], dtype=int64), array([1, 2, 3, 4, 0, 3, 0, 1, 3, 4, 0, 1, 2, 3, 4, 2, 3, 4], dtype=int64))
Selected elements using advanced indexing:
 [75 88 60 91 82 72 51 94 82 66 64 51 89 92 75 74 63 83]

Explanation:

  • Import Libraries:
    • Imported numpy as "np" for array creation and manipulation.
  • Create 2D NumPy Array:
    • Create a 2D NumPy array named array_2d with random integers ranging from 0 to 99 and a shape of (5, 5).
  • Define Condition:
    • Define a condition to select elements in the array that are greater than 50 using boolean indexing.
  • Find Indices with np.nonzero:
    • Use np.nonzero to find the indices of elements that satisfy the condition.
  • Advanced Indexing with Indices:
    • Applied advanced indexing using the indices obtained from np.nonzero to select the elements that meet the condition.
  • Print Results:
    • Print the original 2D array, the boolean condition array, the indices of elements that meet the condition, and the selected elements to verify the operation.

Python-Numpy Code Editor: