在 Numpy 中計算第 n 次離散差分


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

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

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

步驟

首先,匯入所需的庫 -

import numpy as np
import numpy.ma as ma

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

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 Numpy 中使用 MaskedArray.diff() 方法 -

print("
Result..
.", np.diff(maskArr))

示例

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 print("
Result..
.", np.diff(maskArr))

輸出

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年2月5日

310 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告