1. 程式人生 > >np.diff函式

np.diff函式

np.diff函式

覺得有用的話,歡迎一起討論相互學習~Follow Me

陣列中a[n]-a[n-1]

import numpy as np
a=np.array([1, 6, 7, 8, 12])
diff_x1 = np.diff(a)
print("diff_x1",diff_x1)
# diff_x1 [5 1 1 4]
# [6-1,7-6,8-7,12-8]

高維陣列同樣適用

二維陣列

b=np.array([[1, 6, 7, 8, 12],[1, 6, 7, 8, 12]])
diff_x2 = np.diff(b)
print("diff_x2 \n",diff_x2)
# diff_x2
#  [[5 1 1 4]
#  [5 1 1 4]]

高維陣列

c=b.reshape(5,1,2)
diff_x3 = np.diff(c)
print("diff_x3 \n",diff_x3)
# diff_x3
#  [[[  5]] [6-1]
#
#  [[  1]] [8-7]
#
#  [[-11]] [1-12]
#
#  [[  1]] [7-6]
#
#  [[  4]]] [12-8]