Pandas Series: diff() function
First discrete difference of element in Pandas
The diff() function is used to first discrete difference of element.
Calculates the difference of a Series element compared with another element in the Series (default is element in previous row).
Syntax:
Series.diff(self, periods=1)
Parameters:
Name | Description | Type/Default Value | Required / Optional |
---|---|---|---|
periods | Periods to shift for calculating difference, accepts negative values. | int Default Value: 1 |
Required |
Returns: Series
First differences of the Series
Example - Difference with previous row:
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series([2, 2, 3, 4, 5])
s.diff()
Output:
0 NaN 1 0.0 2 1.0 3 1.0 4 1.0 dtype: float64
Example - Difference with 3rd previous row:
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series([2, 2, 3, 4, 5])
s.diff(periods=3)
Output:
0 NaN 1 NaN 2 NaN 3 2.0 4 3.0 dtype: float64
Example - Difference with following row:
Python-Pandas Code:
import numpy as np
import pandas as pd
s = pd.Series([2, 2, 3, 4, 5])
s.diff(periods=-2)
Output:
0 -1.0 1 -2.0 2 -2.0 3 NaN 4 NaN dtype: float64
Previous: Generate descriptive statistics in Pandas
Next: Encode the object in Pandas
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/pandas/series/series-diff.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics