pandas.Series.shift#

Series.shift(periods=1, freq=None, axis=0, fill_value=<no_default>, suffix=None)[源代码]#

按所需的周期数移动索引,并可选择指定时间freq

freq 未传入时,不进行数据对齐地移动索引。如果传入了 freq(此时索引必须是日期或日期时间类型,否则会引发 NotImplementedError),则索引会根据 periodsfreq 进行增加。当 freq 指定为“infer”时,可以推断出 freq,前提是索引的 freq 或 inferred_freq 属性已设置。

参数:
periodsint 或 Sequence

要移动的周期数。可以是正数或负数。如果是一个整数的可迭代对象,数据将按每个整数移动一次。这相当于一次移动一个值并连接所有结果帧。结果列的列名将带有移动的后缀。对于多个周期,axis 不能为 1。

freqDateOffset, tseries.offsets, timedelta, 或 str,可选

要使用的 tseries 模块的偏移量或时间规则(例如 'EOM')。如果指定了 freq,则会移动索引值但不会重新对齐数据。也就是说,如果您想在移动时扩展索引并保留原始数据,请使用 freq。如果 freq 指定为“infer”,则会从索引的 freq 或 inferred_freq 属性推断出来。如果这两个属性都不存在,则会引发 ValueError。

axis{{0 或 ‘index’, 1 或 ‘columns’, None}},默认 None

移动方向。对于 Series,此参数未使用,默认为 0。

fill_valueobject,可选

用于新引入的缺失值标量。默认值取决于 self 的 dtype。对于布尔值和数值 NumPy 数据类型,使用 np.nan。对于 datetime、timedelta 或 period 数据等,使用 NaT。对于扩展 dtype,使用 self.dtype.na_value

suffixstr,可选

如果为 str 且 periods 为可迭代对象,则此字符串将添加到每个移位列名的列名之后、移动值之前。对于 Series,此参数未使用,默认为 None

返回:
Series/DataFrame

输入对象的副本,已移动。

另请参阅

Index.shift

移动 Index 的值。

DatetimeIndex.shift

移动 DatetimeIndex 的值。

PeriodIndex.shift

移动 PeriodIndex 的值。

示例

>>> df = pd.DataFrame(
...     [[10, 13, 17], [20, 23, 27], [15, 18, 22], [30, 33, 37], [45, 48, 52]],
...     columns=["Col1", "Col2", "Col3"],
...     index=pd.date_range("2020-01-01", "2020-01-05"),
... )
>>> df
            Col1  Col2  Col3
2020-01-01    10    13    17
2020-01-02    20    23    27
2020-01-03    15    18    22
2020-01-04    30    33    37
2020-01-05    45    48    52
>>> df.shift(periods=3)
            Col1  Col2  Col3
2020-01-01   NaN   NaN   NaN
2020-01-02   NaN   NaN   NaN
2020-01-03   NaN   NaN   NaN
2020-01-04  10.0  13.0  17.0
2020-01-05  20.0  23.0  27.0
>>> df.shift(periods=1, axis="columns")
            Col1  Col2  Col3
2020-01-01   NaN    10    13
2020-01-02   NaN    20    23
2020-01-03   NaN    15    18
2020-01-04   NaN    30    33
2020-01-05   NaN    45    48
>>> df.shift(periods=3, fill_value=0)
            Col1  Col2  Col3
2020-01-01     0     0     0
2020-01-02     0     0     0
2020-01-03     0     0     0
2020-01-04    10    13    17
2020-01-05    20    23    27
>>> df.shift(periods=3, freq="D")
            Col1  Col2  Col3
2020-01-04    10    13    17
2020-01-05    20    23    27
2020-01-06    15    18    22
2020-01-07    30    33    37
2020-01-08    45    48    52
>>> df.shift(periods=3, freq="infer")
            Col1  Col2  Col3
2020-01-04    10    13    17
2020-01-05    20    23    27
2020-01-06    15    18    22
2020-01-07    30    33    37
2020-01-08    45    48    52
>>> df["Col1"].shift(periods=[0, 1, 2])
            Col1_0  Col1_1  Col1_2
2020-01-01      10     NaN     NaN
2020-01-02      20    10.0     NaN
2020-01-03      15    20.0    10.0
2020-01-04      30    15.0    20.0
2020-01-05      45    30.0    15.0