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

NumpyServer Side ProgrammingProgramming

#### Python Data Science basics with Numpy, Pandas and Matplotlib

Most Popular

63 Lectures 6 hours

#### Data Analysis using NumPy and Pandas

19 Lectures 8 hours

#### Numpy with Python

Most Popular

12 Lectures 3 hours

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)


To mask rows and/or columns of a 2D array that contain masked values, use the np.ma.mask_rowcols() −

print("Result...",np.ma.mask_rowcols(maskArr, axis = -1))

## 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
# The axis is set using the axis parameter
print("Result...",np.ma.mask_rowcols(maskArr, axis = -1))

## 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...
[[-- -- 81]
[-- -- 39]
[-- -- 51]
[-- -- 67]]
Updated on 22-Feb-2022 07:52:18