在Python中计算沿轴1的第n阶离散差分
要计算第n阶离散差分,可以使用numpy.diff()方法。一阶差分由out[i] = a[i+1] - a[i]给出,沿给定轴计算,高阶差分通过递归使用diff计算。diff()方法返回第n阶差分。输出的形状与a相同,除了轴的维度比原来小n。输出的类型与a中任意两个元素差的类型相同。在大多数情况下,这与a的类型相同。一个显著的例外是datetime64,它会导致timedelta64输出数组。
第一个参数是输入数组。第二个参数是n,即值差分的次数。如果为零,则按原样返回输入。第三个参数是取差分的轴,默认为最后一个轴。第四个参数是在执行差分之前,预先添加到输入数组沿轴上的值。标量值会扩展到数组,在轴方向上长度为1,在所有其他轴上与输入数组的形状相同。
步骤
首先,导入所需的库:
import numpy as np
使用array()方法创建一个numpy数组。我们添加了int类型的元素和nan:
arr = np.array([[10, 15, 30, 65], [80, 87, np.nan, 120]])
显示数组:
print("Our Array...\n",arr)
检查维度:
print("\nDimensions of our Array...\n",arr.ndim)
获取数据类型:
print("\nDatatype of our Array object...\n",arr.dtype)
要计算第n阶离散差分,可以使用numpy.diff()方法。一阶差分由out[i] = a[i+1] - a[i]给出,沿给定轴计算,高阶差分通过递归使用diff计算:
print("\nDiscrete difference..\n",np.diff(arr, axis = 1))
示例
import numpy as np # Creating a numpy array using the array() method # We have added elements of int type with nan arr = np.array([[10, 15, 30, 65], [80, 87, np.nan, 120]]) # Display the array print("Our Array...\n",arr) # Check the Dimensions print("\nDimensions of our Array...\n",arr.ndim) # Get the Datatype print("\nDatatype of our Array object...\n",arr.dtype) # To calculate the n-th discrete difference, use the numpy.diff() method # 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. print("\nDiscrete difference..\n",np.diff(arr, axis = 1))
输出
Our Array... [[ 10. 15. 30. 65.] [ 80. 87. nan 120.]] Dimensions of our Array... 2 Datatype of our Array object... float64 Discrete difference.. [[ 5. 15. 35.] [ 7. nan nan]]
广告