w3resource

Create a Masked array and Mask a row in NumPy

NumPy: Masked Arrays Exercise-8 with Solution

Write a NumPy program to create a masked array from a 2D NumPy array and mask all values in a specified row.

Sample Solution:

Python Code:

import numpy as np
import numpy.ma as ma

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

# Specify the row to mask
row_to_mask = 2

# Create a masked array from the 2D array and mask all values in the specified row
masked_array = ma.masked_array(array_2d, mask=np.zeros_like(array_2d, dtype=bool))
masked_array[row_to_mask] = ma.masked

# Print the original array and the masked array
print('Original 2D array:\n', array_2d)
print('Masked array (with row {} masked):\n'.format(row_to_mask), masked_array)

Output:

Original 2D array:
 [[5 4 4 0]
 [0 1 3 2]
 [6 7 5 1]
 [5 7 3 2]]
Masked array (with row 2 masked):
 [[5 4 4 0]
 [0 1 3 2]
 [-- -- -- --]
 [5 7 3 2]]

Explanation:

  • Import Libraries:
    • Imported numpy as "np" for array creation and manipulation.
    • Imported numpy.ma as "ma" for creating and working with masked arrays.
  • Create 2D NumPy Array:
    • Create a 2D NumPy array named 'array_2d' with random integers ranging from 0 to 9 and a shape of (4, 4).
  • Specify Row to Mask:
    • Specify the row index to mask, which is 2 in this example.
  • Create Masked Array:
    • Create a masked array from the 2D array using ma.masked_array. Initially, set the mask to be an array of False values with the same shape as the original array.
    • Masked all values in the specified row by setting the mask for that row to True.
  • Print the original 2D array and the masked array with the specified row masked.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Element-wise addition of two Masked arrays in NumPy.
Next: Mask elements in NumPy array based on condition using Logical operations.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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/create-a-masked-array-and-mask-a-row-in-numpy.php