在NumPy中返回元素級基掩碼陣列,該陣列由第二個陣列的冪構成


要返回元素級基陣列,其冪來自第二個陣列,請在Python NumPy中使用**MaskedArray.power()**方法。

where引數是在輸入上廣播的條件。在條件為True的位置,輸出陣列將設定為ufunc結果。在其他地方,輸出陣列將保留其原始值。請注意,如果透過預設的out=None建立未初始化的輸出陣列,則其中條件為False的位置將保持未初始化狀態。

out引數是儲存結果的位置。如果提供,它必須具有輸入廣播到的形狀。如果未提供或為None,則返回一個新分配的陣列。元組(僅可能作為關鍵字引數)的長度必須等於輸出的數量。

步驟

首先,匯入所需的庫:

import numpy as np
import numpy.ma as ma

使用numpy.array()方法建立一個包含整數元素的陣列:

arr = np.array([93, 33, 76, 73, 88, 51, 62, 45, 67])
print("Array...
", arr)

建立一個掩碼陣列並將其中一些標記為無效:

maskArr = ma.masked_array(arr, mask =[ 0, 0, 0, 0, 1, 0, 0, 1, 1])
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("
Number of elements in the Masked Array...
",maskArr.size)

設定冪陣列:

arrPower = [2, 3, 4, 2, 4, 3, 5, 3, 2]

要返回元素級基陣列,其冪來自第二個陣列,請使用MaskedArray.power()方法:

resArr = np.ma.power(maskArr, arrPower)
print("
Resultant Array..
.", resArr)

示例

import numpy as np
import numpy.ma as ma

# Create an array with int elements using the numpy.array() method
arr = np.array([93, 33, 76, 73, 88, 51, 62, 45, 67])
print("Array...
", arr) # Create a masked array and mask some of them as invalid maskArr = ma.masked_array(arr, mask =[ 0, 0, 0, 0, 1, 0, 0, 1, 1]) print("
Our Masked Array...
", maskArr) # Get the type of the masked array 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("
Number of elements in the Masked Array...
",maskArr.size) # Set the power array arrPower = [2, 3, 4, 2, 4, 3, 5, 3, 2] # To return element-wise base array raised to power from second array, use the MaskedArray.power() method in Python Numpy resArr = np.ma.power(maskArr, arrPower) print("
Resultant Array..
.", resArr)

輸出

Array...
[93 33 76 73 88 51 62 45 67]

Our Masked Array...
[93 33 76 73 -- 51 62 -- --]

Our Masked Array type...
int64

Our Masked Array Dimensions...
1

Our Masked Array Shape...
(9,)

Number of elements in the Masked Array...
9

Resultant Array..
. [8649 35937 33362176 5329 -- 132651 916132832 -- --]

更新於:2022年2月5日

170 次檢視

啟動您的職業生涯

完成課程獲得認證

開始
廣告