📌  相关文章
📜  如何使用 NumPy 计算数组中相邻元素之间的差异

📅  最后修改于: 2022-05-13 01:54:21.613000             🧑  作者: Mango

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

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

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

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

示例 1:

Python3
# 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)


Python3
# 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)


Python3
# 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)


输出:

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

示例 2:

Python3

# 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:

Python3

# 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]]