pandas.Series.diff#

Series.diff(periods=1)[源代码]#

元素的离散差分。

计算 Series 元素与 Series 中另一个元素(默认是上一行中的元素)之间的差值。

Parameters:
periodsint, 默认值 1

用于计算差值的向前(或向后)移动的周期数,接受负值。

Returns:
Series

Series 的一阶差分。

参见

Series.pct_change

指定周期数内的百分比变化。

Series.shift

使用可选的时间频率,将索引向前(或向后)移动指定的周期数。

DataFrame.diff

离散的一阶差分。

Notes

对于布尔 dtype,这使用 operator.xor() 而不是 operator.sub() 。结果根据 Series 中的当前 dtype 计算,但是结果的 dtype 始终是 float64。

Examples

与前一行的差值

>>> s = pd.Series([1, 1, 2, 3, 5, 8])
>>> s.diff()
0    NaN
1    0.0
2    1.0
3    1.0
4    2.0
5    3.0
dtype: float64

与第三行前的差值

>>> s.diff(periods=3)
0    NaN
1    NaN
2    NaN
3    2.0
4    4.0
5    6.0
dtype: float64

与后一行的差值

>>> s.diff(periods=-1)
0    0.0
1   -1.0
2   -1.0
3   -2.0
4   -3.0
5    NaN
dtype: float64

输入数据类型溢出

>>> s = pd.Series([1, 0], dtype=np.uint8)
>>> s.diff()
0      NaN
1    255.0
dtype: float64