w3resource

Replace elements in 2D NumPy array using Boolean Indexing


Replacing Elements with Boolean Indexing:

Write a NumPy program that creates a 2D NumPy array and uses boolean indexing to replace all elements that meet a certain condition with a specified value.

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 replace elements greater than 50
condition = array_2d > 50

# Define the value to replace the elements that meet the condition
replacement_value = -1

# Use boolean indexing to replace elements that meet the condition
array_2d[condition] = replacement_value

# Print the modified array
print('Modified 2D array:\n', array_2d)

Output:

Modified 2D array:
 [[-1 16 36 28 13]
 [-1 39 39 -1 -1]
 [37 -1 -1 -1 19]
 [-1 -1  8 35  9]
 [-1 -1 29 44 -1]]

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 replace elements greater than 50 using boolean indexing.
  • Define Replacement Value:
    • Set the replacement value to -1 for elements that meet the condition.
  • Boolean Indexing for Replacement:
    • Applied boolean indexing to replace elements in array_2d that are greater than 50 with the specified replacement value.
  • Print Results:
    • Print the modified 2D array to verify that the elements meeting the condition were replaced.

Python-Numpy Code Editor: