在 Numpy 中計算特定軸上的第 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 或附加到 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 次離散差分,請使用 MaskedArray.diff() 方法。第一個差分由 out[i] = a[i+1] - a[i] 給出,沿著給定的軸,更高的差分是透過遞迴使用 diff 計算的。軸是使用“axis”引數設定的。軸是取差分的軸,預設為最後一個軸

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

示例

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 Nump # 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 = 1))

輸出

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..
. [[-- 13]
[-60 43]
[-- --]
[-17 22]]

更新於: 2022-02-05

122 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告