# Return each element of the masked array rounded in Numpy

To return each element rounded, use the ma.MaskedArray.around() method in Python Numpy. The decimals parameter are the number of decimal places to round to (default: 0). If decimals is negative, it specifies the number of positions to the left of the decimal point.

The out parameter is an alternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary. See Output type determination for more details.

The around() method returns an array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned.

## 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([[49, 85, 45], [67, 33, 59]])
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 =[[0, 0, 1], [ 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 return each element rounded, use the ma.MaskedArray.around() method in Numpy −

print("Result...", np.around(maskArr))

## Example

# Python ma.MaskedArray - Return each element of the masked array rounded

import numpy as np
import numpy.ma as ma

# Create an array with int elements using the numpy.array() method
arr = np.array([[55.50, 85.35, 68.78, 84], [67.96, 33.35, 39.76,53.20]])
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

# Get the dimensions of the Masked Array

# Get the shape of the Masked Array

# Get the number of elements of the Masked Array

# To return each element rounded, use the ma.MaskedArray.around() method in Numpy.
print("Result...", np.around(maskArr))

## Output

Array...
[[55.5 85.35 68.78 84. ]
[67.96 33.35 39.76 53.2 ]]

Array type...
float64

Array Dimensions...
2

[[-- -- 68.78 84.0]
[67.96 -- 39.76 53.2]]

float64

2

(2, 4)

8

Result...
[[-- -- 69.0 84.0]
[68.0 -- 40.0 53.0]]

Updated on: 02-Feb-2022

82 Views 