# Return each element of the masked array rounded to the nearest given number of decimals in NumPy

NumpyServer Side ProgrammingProgramming

To return each element rounded to the given number of decimals, use the ma.MaskedArray.around() method in Numpy. Set the number of decimal places to round using the "decimals" parameter.

The decimals parameter is 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([[55.50, 85.35, 68.78, 84], [67.96, 33.35, 39.76, 53.20]])
print("Array...\n", arr)
print("\nArray type...\n", arr.dtype)

Get the dimensions of the Array −

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


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

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

Get the dimensions of the Masked Array −

print("\nOur Masked Array Dimensions...\n",maskArr.ndim)


Get the shape of the Masked Array −

print("\nOur Masked Array Shape...\n",maskArr.shape)

Get the number of elements of the Masked Array −

print("\nElements in the Masked Array...\n",maskArr.size)


To return each element rounded to the given number of decimals, use the ma.MaskedArray.around() method in Numpy. Set the number of decimal places to round using the "decimals" parameter −

print("\nResult...\n", np.around(maskArr, decimals = 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([[55.50, 85.35, 68.78, 84], [67.96, 33.35, 39.76, 53.20]])
print("Array...\n", arr)
print("\nArray type...\n", arr.dtype)

# Get the dimensions of the Array
print("\nArray Dimensions...\n",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 to the given number of decimals, use the ma.MaskedArray.around() method in Numpy.
# Set the number of decimal places to round using the "decimals" parameter
print("\nResult...\n", np.around(maskArr, decimals = 1))

## 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

[68.0 -- 39.8 53.2]]