# Mask rows and/or columns of a 2D array that contain masked values in Numpy

To mask rows and/or columns of a 2D array that contain masked values, use the np.ma.mask_rowcols() method in Numpy. The function returns a modified version of the input array, masked depending on the value of the axis parameter.

Mask whole rows and/or columns of a 2D array that contain masked values. The masking behavior is selected using the axis parameter −

• If axis is None, rows and columns are masked.
• If axis is 0, only rows are masked.
• If axis is 1 or -1, only columns are masked.

## Steps

At first, import the required library −

import numpy as np
import numpy.ma as ma

Create an array with int elements using the numpy.array() method −

arr = np.array([[65, 68, 81], [93, 33, 39], [73, 88, 51], [62, 45, 67]])
print("Array...", arr)
print("Array type...", arr.dtype)

Get the dimensions of the Array −

print("Array Dimensions...",arr.ndim)


Create a masked array and mask some of them as invalid −

maskArr = ma.masked_array(arr, mask =[[1, 1, 0], [ 0, 0, 0], [0, 1, 0], [0, 1, 0]])
print("Our Masked Array type...", maskArr.dtype)

Get the dimensions of the Masked Array −

print("Our Masked Array Dimensions...",maskArr.ndim)


Get the shape of the Masked Array −

print("Our Masked Array Shape...",maskArr.shape)

Get the number of elements of the Masked Array −

print("Elements in the Masked Array...",maskArr.size)


print("Result...",np.ma.mask_rowcols(maskArr))

## Example

import numpy as np
import numpy.ma as ma

# Create an array with int elements using the numpy.array() method
arr = np.array([[65, 68, 81], [93, 33, 39], [73, 88, 51], [62, 45, 67]])
print("Array...", arr)
print("Array type...", arr.dtype)

# Get the dimensions of the Array
print("Array Dimensions...",arr.ndim)

# Create a masked array and mask some of them as invalid
maskArr = ma.masked_array(arr, mask =[[1, 1, 0], [ 0, 0, 0], [0, 1, 0], [0, 1, 0]])

# Get the dimensions of the Masked Array

# Get the shape of the Masked Array

# Get the number of elements of the Masked Array

# To mask rows and/or columns of a 2D array that contain masked values, use the np.ma.mask_rowcols() method in Numpy
print("Result...",np.ma.mask_rowcols(maskArr))

## Output

Array...
[[65 68 81]
[93 33 39]
[73 88 51]
[62 45 67]]

Array type...
int64

Array Dimensions...
2

[[-- -- 81]
[93 33 39]
[73 -- 51]
[62 -- 67]]

int64

2

(4, 3)

12

Result...
[[-- -- --]
[-- -- 39]
[-- -- --]
[-- -- --]]

Updated on: 04-Feb-2022

2K+ Views