在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]]
广告