在 Numpy 中计算轴 1 上的掩盖元素数量
要计算轴 1 上的掩盖元素数量,可以使用ma.MaskedArray.count_masked() 方法。轴使用“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 = 1))
示例
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 = 1))输出
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 1 2 3]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP