- API reference
- Series
- pandas.Series.diff
pandas.Series.diff#
- Series.diff(periods=1)[source]#
First discrete difference of element.
Calculates the difference of a Series element compared with anotherelement in the Series (default is element in previous row).
- Parameters:
- periodsint, default 1
Periods to shift for calculating difference, accepts negativevalues.
- Returns:
- Series
First differences of the Series.
See also
Series.pct_change
Percent change over given number of periods.
Series.shift
Shift index by desired number of periods with an optional time freq.
DataFrame.diff
First discrete difference of object.
Notes
For boolean dtypes, this uses
operator.xor()
rather thanoperator.sub()
.The result is calculated according to current dtype in Series,however dtype of the result is always float64.Examples
Difference with previous row
>>>s=pd.Series([1,1,2,3,5,8])>>>s.diff()0 NaN1 0.02 1.03 1.04 2.05 3.0dtype: float64
Difference with 3rd previous row
>>>s.diff(periods=3)0 NaN1 NaN2 NaN3 2.04 4.05 6.0dtype: float64
Difference with following row
>>>s.diff(periods=-1)0 0.01 -1.02 -1.03 -2.04 -3.05 NaNdtype: float64
Overflow in input dtype
>>>s=pd.Series([1,0],dtype=np.uint8)>>>s.diff()0 NaN1 255.0dtype: float64
On this page