使用 Numpy 中現有陣列的屬性來清空掩碼陣列


要使用現有陣列的屬性來清空掩碼陣列,請在 Python Numpy 中使用 ma.masked_all_like() 方法。掩碼陣列是標準 numpy.ndarray 和掩碼的組合。掩碼可以為無掩碼(表示相關聯的陣列中沒有值無效)或布林值陣列,它決定了相關聯的陣列的每個元素是有效還是無效。

步驟

首先,匯入必需的庫 −

import numpy as np
import numpy.ma as ma

使用 Python Numpy 中的 numpy.array() 方法建立一個新陣列 −

arr = np.array([[77, 51, 92], [56, 31, 69], [73, 88, 51], [62, 45, 67]], dtype=np.float32)

顯示我們的陣列 −

print("Array...
",arr)

獲取資料型別 −

print("
Array datatype...
",arr.dtype)

要使用現有陣列的屬性來清空掩碼陣列,請使用 ma.masked_all_like() −

arr = ma.masked_all_like(arr)

顯示我們的陣列 −

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

獲取資料型別 −

print("
New Array datatype...
",arr.dtype)

獲取陣列的維度 −

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

獲取陣列的形狀 −

print("
Our Array Shape...
",arr.shape)

獲取陣列的元素數量 −

print("
Elements in the Array...
",arr.size)

示例

# Python ma.MaskedArray - Empty masked array with the properties of an existing array

import numpy as np
import numpy.ma as ma

# Create a new array using the numpy.array() method in Python Numpy
arr = np.array([[77, 51, 92], [56, 31, 69], [73, 88, 51], [62, 45, 67]], dtype=np.float32)

# Displaying our array
print("Array...
",arr) # Get the datatype print("
Array datatype...
",arr.dtype) # To empty masked array with the properties of an existing array, use the ma.masked_all_like() method in Python Numpy arr = ma.masked_all_like(arr) # Displaying our array print("
New Array...
",arr) # Get the datatype print("
New Array datatype...
",arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Elements in the Array...
",arr.size)

輸出

Array...
[[77. 51. 92.]
[56. 31. 69.]
[73. 88. 51.]
[62. 45. 67.]]

Array datatype...
float32

New Array...
[[-- -- --]
[-- -- --]
[-- -- --]
[-- -- --]]

New Array datatype...
float32

Array Dimensions...
2
Our Array Shape...
(4, 3)
Elements in the Array...
12

更新日期:03-Feb-2022

228 次瀏覽

啟動你的 事業

完成課程並獲得認證

開始
廣告