在NumPy中計算沿軸1的第n階離散差分
要計算沿給定軸的第n階離散差分,請在Python NumPy中使用**MaskedArray.diff()**方法。沿給定軸的第一階差分由**out[i] = a[i+1] - a[i]**給出,更高階的差分是透過遞迴使用diff計算的。
- 軸透過“axis”引數設定。
- 軸是計算差分的軸,預設為最後一個軸。
該函式返回第n階差分。輸出的形狀與a相同,只是在axis軸上的維度減小了n。輸出的型別與a的任意兩個元素之間的差分的型別相同。在大多數情況下,這與a的型別相同。一個顯著的例外是datetime64,它會導致timedelta64輸出陣列。
prepend和append引數是在執行差分之前沿axis軸預先新增到a或附加到a的值。標量值將擴充套件為在axis方向上長度為1,並且沿所有其他軸具有輸入陣列形狀的陣列。否則,維度和形狀必須與a匹配,除了axis軸。
步驟
首先,匯入所需的庫:
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()方法。沿給定軸的第一階差分由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]]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP