當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python numpy.diff()用法及代碼示例


numpy.diff(arr[, n[, axis]])當我們計算沿給定軸的n-th階離散離散時,使用函數。沿給定軸的一階差由out [i] = arr [i + 1]-arr [i]給出。如果必須計算更高的差異,則可以遞歸使用diff。

Synatx: numpy.diff()

參數:
arr : [array_like] Input array.
n : [int, optional] The number of times values are differenced.
axis : [int, optional] The axis along which the difference is taken, default is the last axis.



返回: [ndarray]The n-th discrete difference. The output is the same as a except along axis where the dimension is smaller by 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]]


相關用法


注:本文由純淨天空篩選整理自sanjoy_62大神的英文原創作品 numpy.diff() in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。