返回 NumPy 中掩碼陣列的每個四捨五入後的元素


要返回每個四捨五入後的元素,請在 Python NumPy 中使用 **ma.MaskedArray.around()** 方法。decimals 引數是要舍入到的十進位制位數(預設值:0)。如果 decimals 為負數,則它指定小數點左側的位置數。

out 引數是放置結果的備用輸出陣列。它必須與預期輸出具有相同的形狀,但如果需要,輸出值的型別將被強制轉換。有關詳細資訊,請參閱輸出型別確定。

around() 方法返回一個與 a 型別相同的陣列,其中包含四捨五入的值。除非指定了 out,否則會建立一個新陣列。返回對結果的引用。

步驟

首先,匯入所需的庫:

import numpy as np
import numpy.ma as ma

使用 numpy.array() 方法建立一個包含整數元素的陣列:

arr = np.array([[49, 85, 45], [67, 33, 59]])
print("Array...
", arr) print("
Array type...
", arr.dtype)

獲取陣列的維度:

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

建立一個掩碼陣列並將其中一些標記為無效:

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

獲取掩碼陣列的維度:

print("
Our Masked Array Dimensions...
",maskArr.ndim)

獲取掩碼陣列的形狀:

print("
Our Masked Array Shape...
",maskArr.shape)

獲取掩碼陣列的元素個數:

print("
Elements in the Masked Array...
",maskArr.size)

要返回每個四捨五入後的元素,請在 NumPy 中使用 ma.MaskedArray.around() 方法:

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

示例

# 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 maskArr = ma.masked_array(arr, mask =[[1, 1, 0, 0], [0, 1, 0, 0]]) print("
Our Masked Array
", maskArr) 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))

輸出

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

Array type...
float64

Array Dimensions...
2

Our Masked Array
[[-- -- 68.78 84.0]
[67.96 -- 39.76 53.2]]

Our Masked Array type...
float64

Our Masked Array Dimensions...
2

Our Masked Array Shape...
(2, 4)

Elements in the Masked Array...
8

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

更新於:2022年2月2日

瀏覽量:138

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.