在 Python ma.MaskedArray 中计算沿轴 0 的第 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 的值。标量值扩展为沿轴方向长度为 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 个离散差分,请在 Python 中使用 MaskedArray.diff() 方法。第一个差分由 out[i] = a[i+1] - a[i] 沿给定轴给出,较高的差分是通过递归使用 diff 计算的。轴使用“axis”参数设置。轴是取差分的轴,默认为最后一个轴 -
print("
Result..
.", np.diff(maskArr, axis = 0))
示例
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 Numpy # 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 = 0))
输出
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.. . [[-- -35 -5] [-20 -- -25] [-11 -- 16]]
广告