將掩碼陣列的元素複製到標準 Python 標量並返回它
要將陣列的元素複製到標準 Python 標量並返回它,請在 Numpy 中使用 **ma.MaskedArray.item()** 方法。
*args 引數,如果
無 - 在這種情況下,該方法僅適用於只有一個元素的陣列 (a.size == 1),該元素被複制到標準 Python 標量物件中並返回。
int_type - 此引數被解釋為陣列中的平面索引,指定要複製和返回的元素。
int_type 元組 - 功能與單個 int_type 引數相同,只是該引數被解釋為陣列中的 nd 索引。
步驟
首先,匯入所需的庫 -
import numpy as np import numpy.ma as ma
使用 numpy.array() 方法建立具有 int 元素的陣列 -
arr = np.array([[55, 85, 59, 77], [67, 33, 39, 57], [29, 88, 51, 37], [56, 45, 99, 85]])
print("Array...
", arr)
print("
Array type...
", arr.dtype)獲取陣列的維度 -
print("
Array Dimensions...
",arr.ndim)建立一個掩碼陣列並將其中的某些元素標記為無效 -
maskArr = ma.masked_array(arr, mask =[[1, 1, 0, 0], [ 0, 0, 1, 0], [0, 0, 0, 1], [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)
要將陣列的元素複製到標準 Python 標量並返回它,請在 Numpy 中使用 ma.MaskedArray.item() 方法 -
print("
Result...
",maskArr.item(7))示例
# Python ma.MaskedArray - Copy an element of an array to a standard Python scalar and return it
import numpy as np
import numpy.ma as ma
# Create an array with int elements using the numpy.array() method
arr = np.array([[55, 85, 59, 77], [67, 33, 39, 57], [29, 88, 51, 37], [56, 45, 99, 85]])
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, 0, 1, 0], [0, 0, 0, 1], [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 copy an element of an array to a standard Python scalar and return it, use the ma.MaskedArray.item() method in Numpy
print("
Result...
",maskArr.item(7))輸出
Array... [[55 85 59 77] [67 33 39 57] [29 88 51 37] [56 45 99 85]] Array type... int64 Array Dimensions... 2 Our Masked Array [[-- -- 59 77] [67 33 -- 57] [29 88 51 --] [56 -- 99 85]] Our Masked Array type... int64 Our Masked Array Dimensions... 2 Our Masked Array Shape... (4, 4) Elements in the Masked Array... 16 Result... 57
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP