返回 NumPy 中填充給定值的掩碼陣列的副本


要返回自我的副本,其中掩碼值填充了給定的值,請使用 ma.MaskedArray.filled() 方法。**“fill_value”** 引數是要用於無效條目的值。可以是標量或非標量。

fill_value 是用於無效條目的值。可以是標量或非標量。如果是非標量,則結果 ndarray 必須能夠廣播到輸入陣列上。預設為 None,在這種情況下,將改為使用陣列的 fill_value 屬性。

該方法返回自我的副本,其中無效條目替換為 *fill_value*(無論是函式引數還是自我的屬性),或者如果沒有任何無效條目需要替換,則返回自我本身作為 ndarray。

步驟

首先,匯入所需的庫 -

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)

返回自我的副本,其中掩碼值填充了給定的值,使用 ma.MaskedArray.filled() 方法。 "fill_value" 引數是要用於無效條目的值。可以是標量或非標量 -

print("
Return Value...
",maskArr.filled(fill_value = 111))

示例

# Python ma.MaskedArray - Return a copy of self, with masked values filled with a given value

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 return a copy of self, with masked values filled with a given value, use the ma.MaskedArray.filled() method # The "fill_value" parameter is the value to use for invalid entries. Can be scalar or non-scalar. # If non-scalar, the resulting ndarray must be broadcastable over input array print("
Return Value...
",maskArr.filled(fill_value = 111))

輸出

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

Return Value...
[[ 49 85 111]
[ 67 111 59]]

更新於: 2022年2月2日

97 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.