獲取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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP