在 Numpy 中計算沿著軸 0 的掩碼元素數量
若要統計特定軸上掩碼元素的數量,請使用ma.MaskedArray.count_masked()方法。 軸 0 使用“axis”引數設定。 該方法返回掩碼元素總數(axis=None)或給定軸的每個切片的掩碼元素數。
axis 引數是在其上進行計數的軸。 如果是 None(預設值),則使用陣列的扁平版本。
步驟
首先,匯入需要的庫 −
import numpy as np import numpy.ma as ma
使用 numpy.arange() 方法建立一個包含 int 元素的 4x4 陣列 −
arr = np.arange(16).reshape((4,4))
print("Array...
", arr)
print("
Array type...
", arr.dtype)獲取陣列的維度 −
print("
Array Dimensions...
",arr.ndim)
print("
Our Array type...
", arr.dtype)獲取陣列的形狀 −
print("
Our Masked Array Shape...
",arr.shape)
獲取陣列的元素數量 −
print("
Elements in the Masked Array...
",arr.size)建立一個掩碼陣列 −
arr = ma.array(arr) arr[0, 1] = ma.masked arr[1, 1] = ma.masked arr[2, 1] = ma.masked arr[2, 2] = ma.masked arr[3, 0] = ma.masked arr[3, 2] = ma.masked arr[3, 3] = ma.masked
若要統計特定軸上掩碼元素的數量,請使用 ma.MaskedArray.count_masked() 方法。 軸使用“axis”引數設定
print("
Result (number of masked elements)...
",ma.count_masked(arr, axis = 0))
示例
# Python ma.MaskedArray - Count the number of masked elements along axis 0 to count
import numpy as np
import numpy.ma as ma
# Creating a 4x4 array with int elements using the numpy.arange() method
arr = np.arange(16).reshape((4,4))
print("Array...
", arr)
print("
Array type...
", arr.dtype)
# Get the dimensions of the Array
print("
Array Dimensions...
",arr.ndim)
print("
Our Array type...
", arr.dtype)
# Get the shape of the Array
print("
Our Masked Array Shape...
",arr.shape)
# Get the number of elements of the Array
print("
Elements in the Masked Array...
",arr.size)
# Create a masked array
arr = ma.array(arr)
arr[0, 1] = ma.masked
arr[1, 1] = ma.masked
arr[2, 1] = ma.masked
arr[2, 2] = ma.masked
arr[3, 0] = ma.masked
arr[3, 2] = ma.masked
arr[3, 3] = ma.masked
# To count the number of masked elements along specific axis, use the ma.MaskedArray.count_masked() method
# The axis is set using the "axis" parameter
print("
Result (number of masked elements)...
",ma.count_masked(arr, axis = 0))輸出
Array... [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] Array type... int64 Array Dimensions... 2 Our Array type... int64 Our Masked Array Shape... (4, 4) Elements in the Masked Array... 16 Result (number of masked elements)... [1 3 2 1]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP