diff()
函数计算数组沿指定轴的连续元素之间的差值。
示例
import numpy as np
array1 = np.array([1, 3, 6, 10, 15])
# use diff() to calculate difference of consecutive elements of array1
result = np.diff(array1)
print(result)
# Output: [2 3 4 5]
diff() 语法
diff()
的语法是:
numpy.diff(array, n=1, axis=-1)
diff() 参数
diff()
函数接受以下参数:
array
- 输入数组n
(可选) - 连续求差的次数axis
(可选) - 计算差值的轴
diff() 返回值
diff()
函数返回一个数组,其中包含沿指定轴的连续元素之间的差值。
示例 1:2-D 数组的 diff()
axis
参数定义了如何在 2-D 数组中查找连续元素的差值。
- 如果
axis
= 0,则按列计算连续元素的差值。 - 如果
axis
= 1,则按行计算连续元素的差值。
import numpy as np
array1 = np.array([[1, 3, 6],
[2, 4, 8]])
# compute the differences between consecutive elements column-wise (along axis 0)
result1 = np.diff(array1, axis=0)
print("Differences along axis 0 (column-wise):")
print(result1)
# compute the differences between consecutive elements row-wise (along axis 1)
result2 = np.diff(array1, axis=1)
print("\nDifferences along axis 1 (row-wise):")
print(result2)
输出
Differences along axis 0 (column-wise): [[1 1 2]] Differences along axis 1 (row-wise): [[2 3] [2 4]]
这里,
- 结果数组 result1 包含 array1 每列的连续元素差值。
- 结果数组 result2 包含 array1 每行的连续元素差值。
示例 2:diff() 中 n 参数的使用
diff()
中的 n
参数允许我们指定连续求差的次数。
默认情况下,n
设置为 1,表示只计算一次连续元素的差值。
import numpy as np
# create a 1D NumPy array
array1 = np.array([1, 4, 9, 16, 25])
# compute the first-order differences by setting n=1
result1 = np.diff(array1, n=1)
print("First-order differences:")
print(result1)
# compute the second-order differences by setting n=2
result2 = np.diff(array1, n=2)
print("\nSecond-order differences:")
print(result2)
输出
First-order differences: [3 5 7 9] Second-order differences: [2 2 2]
在此示例中,
- 结果数组 result1 包含 array1 的连续元素差值。其计算方式为 [4-1, 9-4, 16-9, 25-16],结果为
[3, 5, 7, 9]
。 - 结果数组 result2 包含 result1 的连续元素差值。其计算方式为 [5-3, 7-5, 9-7],结果为
[2, 2, 2]
。