返回 Masked 陣列在 NumPy 中的副本


要返回 Masked 陣列的副本,請在 Python Numpy 中使用 ma.MaskedArray.copy() 方法。order 引數控制副本的記憶體佈局。‘C’表示 C 順序,‘F’表示 F 順序,‘A’表示如果 a 是 Fortran 連續的則為‘F’,否則為‘C’。‘K’表示儘可能與 a 的佈局相匹配。(請注意,此函式和 numpy.copy 非常相似,但 for order = 的預設值不同,並且此函式總是傳遞子類。)

步驟

首先,匯入所需的庫 −

import numpy as np
import numpy.ma as ma

使用 numpy.array() 方法建立包含 int 元素的陣列 −

arr = np.array([[55, 85, 68, 84], [67, 33, 39, 53], [29, 88, 51, 37], [56, 45, 99, 85]])
print("Array...
", arr) print("
Array type...
", arr.dtype)

獲取陣列的維度 −

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

建立一個 Masked 陣列並將其中一些作為無效項進行掩碼 −

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)

獲取 Masked 陣列的維度 −

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

獲取 Masked 陣列的形狀 −

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

獲取 Masked 陣列中的元素數量 −

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

要返回 Masked 陣列的副本,請使用 ma.MaskedArray.copy() 方法 −

resArr = maskArr.copy()
print("
Result...
",resArr)

示例

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, 68, 84], [67, 33, 39, 53], [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 return a copy of the masked array, use the ma.MaskedArray.copy() method resArr = maskArr.copy() print("
Result...
",resArr)

輸出

Array...
[[55 85 68 84]
[67 33 39 53]
[29 88 51 37]
[56 45 99 85]]

Array type...
int64

Array Dimensions...
2

Our Masked Array
[[-- -- 68 84]
[67 33 -- 53]
[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...
[[-- -- 68 84]
[67 33 -- 53]
[29 88 51 --]
[56 -- 99 85]]

更新於: 2022 年 2 月 5 日

359 瀏覽量

開啟您的 職業生涯

完成本課程,獲取認證

開始吧
廣告
© . All rights reserved.