在Python中计算无符号整数数组的n阶差分
要计算n阶差分,可以使用numpy.diff()方法。一阶差分由out[i] = a[i+1] - a[i]给出,沿着给定的轴计算,高阶差分通过递归使用diff计算。第一个参数是输入数组。第二个参数是n,即差分值的次数。如果为零,则按原样返回输入。第三个参数是进行差分的轴,默认为最后一个轴。
第四个参数是在执行差分之前,沿轴预先附加到输入数组或附加到输入数组的值。标量值扩展到沿轴方向长度为1的数组,并且沿所有其他轴的形状与输入数组相同。否则,维度和形状必须与a匹配,除了沿轴方向。
步骤
首先,导入所需的库:
import numpy as np
使用array()方法创建一个numpy数组。我们添加了无符号类型的元素。对于无符号整数数组,结果也将是无符号的:
arr = np.array([1,0], dtype=np.uint8)
显示数组:
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))
示例
import numpy as np # Creating a numpy array using the array() method # We have added elements of unsigned type # For unsigned integer arrays, the results will also be unsigned. arr = np.array([1,0], dtype=np.uint8) # 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))
输出
Our Array... [1 0] Dimensions of our Array... 1 Datatype of our Array object... uint8 Discrete difference.. [255]
广告