在 NumPy 中設定差分次數後計算第 n 次離散差分


要計算沿給定軸的第 n 次離散差分,請在 Python NumPy 中使用 **MaskedArray.diff()** 方法。“n”引數用於設定差分值的次數。如果為零,則按原樣返回輸入。

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

prepend 和 append 引數是在執行差分之前沿軸預先新增到輸入或附加到輸入的值。標量值將擴充套件為沿軸方向長度為 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() 方法。“n”引數用於設定差分值的次數。如果為零,則按原樣返回輸入。

print("
Result..
.", np.diff(maskArr, n = 2))

示例

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 "n" parameter is used to set the number of times values are differenced. # If zero, the input is returned as-is. print("
Result..
.", np.diff(maskArr, n = 2))

輸出

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..
. [[--]
[103]
[--]
[39]]

更新於:2022年2月5日

瀏覽量:121

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告