Create a Boolean Mask from an Array in NumPy



To create a boolean mask from an array, use the ma.make_mask() method in Python Numpy. The function can accept any sequence that is convertible to integers, or nomask. Does not require that contents must be 0s and 1s, values of 0 are interpreted as False, everything else as True.

The dtype is the data-type of the output mask. By default, the output mask has a dtype of MaskType (bool). If the dtype is flexible, each field has a boolean dtype. This is ignored when m is nomask, in which case nomask is always returned.

Steps

At first, import the required library −

import numpy as np import numpy.ma as ma

Create an array with zeros using the numpy.zeros() method in Python Numpy −

arr = np.zeros(7) print("Array...", arr)

To Create a boolean mask from an array, use the ma.make_mask() method in Python Numpy −

print("Masked Array...", ma.make_mask(arr))

Type of Array −

print("Array type...", arr.dtype)

Get the dimensions of the Array −

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

Get the shape of the Array −

print("Our Array Shape...",arr.shape)

Get the number of elements of the Array −

print("Elements in the Array...",arr.size)

Example

Open Compiler
import numpy as np import numpy.ma as ma # Create an array with zeros using the numpy.zeros() method in Python Numpy arr = np.zeros(7) print("Array...", arr) # To Create a boolean mask from an array, use the ma.mask_mask() method in Python Numpy print("Masked Array...", ma.make_mask(arr)) # Type of Array print("Array type...", arr.dtype) # Get the dimensions of the Array print("Array Dimensions...",arr.ndim) # Get the shape of the Array print("Our Array Shape...",arr.shape) # Get the number of elements of the Array print("Elements in the Array...",arr.size)

Output

Array...
[0. 0. 0. 0. 0. 0. 0.]

Masked Array...
False

Array type...
float64

Array Dimensions...
1

Our Array Shape...
(7,)

Elements in the Array...
7
Updated on: 2022-02-04T09:54:19+05:30

279 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements