在 Python ma.MaskedArray 中計算沿軸 0 的第 n 個離散差分


要計算沿給定軸的第 n 個離散差分,請在 Python Numpy 中使用 **MaskedArray.diff()** 方法。沿給定軸的第一個差分由 **out[i] = a[i+1] - a[i]** 給出,較高的差分是透過遞迴使用 diff 計算的 -

  • 軸使用“**axis**”引數設定

  • 軸是取差分的軸,預設為最後一個軸。

該函式返回第 n 個差分。輸出的形狀與 a 相同,除了軸,該軸的維度比 n 小。輸出的型別與 a 的任何兩個元素之間的差分的型別相同。在大多數情況下,這與 a 的型別相同。一個值得注意的例外是 datetime64,它會導致 timedelta64 輸出陣列。

prepend、append 引數是在執行差分之前沿軸預先附加或附加到 a 的值。標量值擴充套件為沿軸方向長度為 1 且沿所有其他軸方向具有輸入陣列形狀的陣列。否則,維度和形狀必須與 a 相同,除了軸。

步驟

首先,匯入所需的庫 -

import numpy as np
import numpy.ma as ma

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

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

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

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

要計算沿給定軸的第 n 個離散差分,請在 Python 中使用 MaskedArray.diff() 方法。第一個差分由 out[i] = a[i+1] - a[i] 沿給定軸給出,較高的差分是透過遞迴使用 diff 計算的。軸使用“axis”引數設定。軸是取差分的軸,預設為最後一個軸 -

print("
Result..
.", np.diff(maskArr, axis = 0))

示例

import numpy as np
import numpy.ma as ma

# Create an array with int elements using the numpy.array() method
arr = np.array([[65, 68, 81], [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 =[[1, 0, 0], [ 0, 0, 0], [0, 1, 0], [0, 0, 0]]) 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) # To calculate the n-th discrete difference along the given axis, use the MaskedArray.diff() method in Python Numpy # The first difference is given by out[i] = a[i+1] - a[i] along the given axis, higher differences are calculated by using diff recursively. # The axis is set using the "axis" parameter # The axis is the axis along which the difference is taken, default is the last axis. print("
Result..
.", np.diff(maskArr, axis = 0))

輸出

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

Our Masked Array...
[[-- 68 81]
[93 33 76]
[73 -- 51]
[62 45 67]]

Our Masked Array type...
int64

Our Masked Array Dimensions...
2

Our Masked Array Shape...
(4, 3)

Number of elements in the Masked Array...
12

Result..
. [[-- -35 -5]
[-20 -- -25]
[-11 -- 16]]

更新於: 2022 年 2 月 5 日

130 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.