
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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