NumPy中將掩碼陣列轉換為靈活型別陣列
要將掩碼陣列轉換為靈活型別陣列,請在NumPy中使用**ma.MaskedArray.toflex()**方法。返回的靈活型別陣列將有兩個欄位:_data欄位儲存陣列的_data部分。
此方法返回一個新的具有兩個欄位的靈活型別ndarray:第一個元素包含一個值,第二個元素包含相應的掩碼布林值。返回的記錄形狀與self.shape匹配。
掩碼陣列是標準numpy.ndarray和掩碼的組合。掩碼可以是nomask(表示關聯陣列中沒有無效值),也可以是布林值陣列,用於確定關聯陣列的每個元素的值是否有效。
步驟
首先,匯入所需的庫:
import numpy as np import numpy.ma as ma
使用numpy.array()方法建立一個包含整數元素的陣列:
arr = np.array([[49, 85, 45], [67, 33, 59]])
print("Array...
", arr)
print("
Array type...
", arr.dtype)獲取陣列的維度:
print("Array Dimensions...
",arr.ndim)
建立一個掩碼陣列並將其中一些標記為無效:
maskArr = ma.masked_array(arr, mask =[[0, 0, 1], [ 0, 1, 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)
要將掩碼陣列轉換為靈活型別陣列,請在NumPy中使用ma.MaskedArray.toflex()方法。返回的靈活型別陣列將有兩個欄位:_data欄位儲存陣列的_data部分:
print("
Result of the transformation...
",maskArr.toflex())示例
# Python ma.MaskedArray - Transform a masked array into a flexibletype array
import numpy as np
import numpy.ma as ma
# Create an array with int elements using the numpy.array() method
arr = np.array([[49, 85, 45], [67, 33, 59]])
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 =[[0, 0, 1], [ 0, 1, 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 transform a masked array into a flexible-type array, use the ma.MaskedArray.toflex() method in Numpy
# The flexible type array that is returned will have two fields: the _data field stores the _data part of the array.
#, the _mask field stores the _mask part of the array.
print("
Result of the transformation...
",maskArr.toflex())輸出
Array... [[49 85 45] [67 33 59]] Array type... int64 Array Dimensions... 2 Our Masked Array [[49 85 --] [67 -- 59]] Our Masked Array type... int64 Our Masked Array Dimensions... 2 Our Masked Array Shape... (2, 3) Elements in the Masked Array... 6 Result of the transformation... [[(49, False) (85, False) (45, True)] [(67, False) (33, True) (59, False)]]
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP