Replace elements in 2D NumPy array using Boolean Indexing
NumPy: Advanced Indexing Exercise-10 with Solution
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:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Cross-Indexing a 2D NumPy array using np.ix_.
Next: Select elements from 3D NumPy array using integer Indexing.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/numpy/replace-elements-in-2d-numpy-array-using-boolean-indexing.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics