如何用NumPy计算数组中相邻元素之间的差异

如何用NumPy计算数组中相邻元素之间的差异

让我们看看如何使用NumPy库计算数组中相邻元素之间的差值。

因此,我们可以用NumPy库的numpy.diff()函数找出相邻元素之间的差异。

语法: numpy.diff(arr, n, axis)

现在,让我们看一个例子。

示例 1:

# import library
import numpy as np
  
# create a numpy 1d-array
arr = np.array([1, 12, 3, 14, 5,
              16, 7, 18, 9, 110])
  
# finding the difference between
# neighboring elements
result = np.diff(arr)
  
print(result)

输出:

[ 11  -9  11  -9  11  -9  11  -9 101]

示例 2:

# import library
import numpy as np
  
# create a numpy 2d-array
arr = np.array([[10, 12, 14], 
                [25, 35, 45],
                [12, 18, 20]])
  
# finding the difference between
# neighboring elements along row
result = np.diff(arr, axis = 1)
  
print(result)

输出:

[[ 2  2]
[10 10]
[ 6  2]]

示例 3:

# import library
import numpy as np
  
# create a numpy 2d-array
arr = np.array([[10, 12, 14], 
                [25, 35, 45],
                [12, 18, 20]])
  
# finding the difference between
# neighboring elements along column
result = np.diff(arr, axis = 0)
  
print(result)

输出:

[[ 15  23  31]
[-13 -17 -25]]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

Numpy 数学函数