Python中的numpy.diff()
numpy.diff(arr[, n[, axis]])函数在我们计算沿给定轴的n阶离散差时使用。一阶差值由out[i] = arr[i+1] – arr[i]沿给定轴给出。如果我们要计算更高的差值,我们要递归地使用diff。
语法: numpy.diff()
参数:
arr : [array_like] 输入阵列。
n : [int, optional] 数值被差异化的次数。
axis : [int, optional] 取差的轴,默认是最后一个轴。
返回: [ndarray]第n个离散差值。其输出与a相同,只是沿轴线的维度要小n。
代码#1:
# Python program explaining
# numpy.diff() method
# importing numpy
import numpy as geek
# input array
arr = geek.array([1, 3, 4, 7, 9])
print("Input array : ", arr)
print("First order difference : ", geek.diff(arr))
print("Second order difference : ", geek.diff(arr, n = 2))
print("Third order difference : ", geek.diff(arr, n = 3))
输出:
Input array : [1 3 4 7 9]
First order difference : [2 1 3 2]
Second order difference : [-1 2 -1]
Third order difference : [ 3 -3]
代码#2:
# Python program explaining
# numpy.diff() method
# importing numpy
import numpy as geek
# input array
arr = geek.array([[1, 2, 3, 5], [4, 6, 7, 9]])
print("Input array : ", arr)
print("Difference when axis is 0 : ", geek.diff(arr, axis = 0))
print("Difference when axis is 1 : ", geek.diff(arr, axis = 1))
输出:
Input array : [[1 2 3 5]
[4 6 7 9]]
Difference with axis 0 : [[3 4 4 4]]
Difference with axis 1 : [[1 1 2]
[2 1 2]]