在 Numpy 中计算特定轴上的第 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 或附加到 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 次离散差分,请使用 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]]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP