返回 NumPy 中掩碼陣列的每個元素,四捨五入到給定的小數位數。
要將每個元素四捨五入到指定的小數位數,請在 NumPy 中使用 **ma.MaskedArray.around()** 方法。使用“**decimals**”引數設定要四捨五入的小數位數。
decimals 引數是要四捨五入到的十進位制位數(預設值:0)。如果 decimals 為負數,則它指定小數點左側的位置數。
out 引數是放置結果的備用輸出陣列。它必須與預期輸出具有相同的形狀,但如果需要,輸出值的型別將被強制轉換。有關詳細資訊,請參閱輸出型別確定。
around() 方法返回一個與 a 型別相同的陣列,其中包含四捨五入的值。除非指定了 out,否則將建立一個新陣列。返回對結果的引用。
步驟
首先,匯入所需的庫 -
import numpy as np import numpy.ma as ma
使用 numpy.array() 方法建立包含 int 元素的陣列 -
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)
獲取陣列的維度 -
print("Array Dimensions...
",arr.ndim)
建立一個掩碼陣列並將其中一些標記為無效 -
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)
獲取掩碼陣列的維度 -
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() 方法。使用“decimals”引數設定要四捨五入的小數位數 -
print("
Result...
", np.around(maskArr, decimals = 1))
示例
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 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("
Result...
", np.around(maskArr, decimals = 1))
輸出
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... [[-- -- 68.8 84.0] [68.0 -- 39.8 53.2]]
廣告