获取NumPy中掩码数组的元素数量


要获取掩码数组的元素数量,请在NumPy中使用**ma.MaskedArray.size**属性。array.size返回一个标准的任意精度Python整数。对于其他获取相同值的方法,情况可能并非如此,这些方法返回的是np.int_的实例,并且如果该值在后续计算中可能会溢出固定大小的整数类型,则这一点可能很重要。

掩码要么是nomask,表示关联数组的任何值均无效,要么是一个布尔数组,用于确定关联数组的每个元素的值是否有效。

步骤

首先,导入所需的库:

import numpy as np
import numpy.ma as ma

使用numpy.array()方法创建数组:

arr = np.array([[35, 85], [67, 33]])
print("Array...
", arr) print("
Array type...
", arr.dtype) print("
Array itemsize...
", arr.itemsize)

获取数组的维度:

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

获取消耗的总字节数:

print("Array nbytes...
",arr.nbytes)

创建一个掩码数组,并将其中一些标记为无效:

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

获取掩码数组的itemsize:

print("
Our Masked Array itemsize...
", maskArr.itemsize)

获取掩码数组的维度:

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

获取掩码数组的形状:

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

获取掩码数组的元素数量,在NumPy中使用ma.MaskedArray.size属性:

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

示例

import numpy as np
import numpy.ma as ma

arr = np.array([[35, 85], [67, 33]])
print("Array...
", arr) print("
Array type...
", arr.dtype) print("
Array itemsize...
", arr.itemsize) # Get the dimensions of the Array print("Array Dimensions...
",arr.ndim) # Get the total bytes consumed print("Array nbytes...
",arr.nbytes) # Create a masked array and mask some of them as invalid maskArr = ma.masked_array(arr, mask =[[0, 0], [ 0, 1]]) print("
Our Masked Array
", maskArr) print("
Our Masked Array type...
", maskArr.dtype) # Get the itemsize of the Masked Array print("
Our Masked Array itemsize...
", maskArr.itemsize) #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) # To get the number of elements of the Masked Array, use the ma.MaskedArray.size attribute in Numpy print("
Elements in the Masked Array...
",maskArr.size)

输出

Array...
[[35 85]
[67 33]]

Array type...
int64

Array itemsize...
8
Array Dimensions...
2
Array nbytes...
32

Our Masked Array
[[35 85]
[67 --]]

Our Masked Array type...
int64

Our Masked Array itemsize...
8

Our Masked Array Dimensions...
2

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

Elements in the Masked Array...
4

更新于: 2022年2月17日

141 次查看

开启你的 职业生涯

完成课程获得认证

立即开始
广告