  # Python | Pandas Series.diff ()

NumPy | Python Methods and Functions

Pandas `Series.diff() ` is used to find differences between items in the same series. The difference is sequential and depends on the period parameter passed to the ` diff () ` method.

Syntax: Series.diff (periods = 1)

Parameters:
periods: integer value, subtracts element before / after period from current element. Negative values ​​are also accepted

Return type: Series

Example:
In this example two series are created from Python lists. The ` diff () ` method is called for both series, once with a positive period and once with a negative value passed to the period parameter.

 ` # pandas module import ` ` import ` ` pandas as pd `   ` # numpy module import ` ` import ` ` numpy as np `   ` # create a list ` ` list ` ` = ` ` [` ` 15 ` `, ` ` 2 ` ` , ` ` 34 ` `, ` ` 12 ` `, ` ` 4 ` `, ` ` 0 ` `, ` ` 9 ` `, ` ` 7 ` `] `   ` # create series ` ` series ` ` = ` ` pd.Series ( list ) ``   # method call with period 2 period2 = series.diff ( 2 )   # Passing a negative value in the period # passing period -1 period_1 = series.diff ( - 1 )   # display print (`Diff with period 2 : {} Diff with period - 1 : {} `. format (period2, period_1)) `

Exit:

` Diff with period 2: 0 NaN 1 NaN 2 19.0 3 10.0 4 -30.0 5 -12.0 6 5.0 7 7.0 dtype: float64 Diff with period -1: 0 13.0 1 -32.0 2 22.0 3 8.0 4 4.0 5 -9.0 6 2.0 7 NaN dtype: float64 `

Explanation: In the first output with a period of 2 digits The i-th position was subtracted from the (i + 2) th position and stored in the (i + 2) th position. In the second output, the value at the i-th position was subtracted from the values ​​in the (i-1) th position and stored in the (i-1) th position.

Note: Values ​​ First / Last n in the output series are equal to NaN depending on the sign of the period (first if the period is positive, and Last if it is negative, where n — period).