pandas.Series.shift#
- Series.shift(periods=1, freq=None, axis=0, fill_value=_NoDefault.no_default, suffix=None)[源代码]#
使用可选的时间 freq 将索引移动指定的周期数。
当未传递 freq 时,在不重新对齐数据的情况下移动索引。如果传递了 freq`(在这种情况下,索引必须是日期或日期时间,否则将引发 `NotImplementedError),则将使用周期和 freq 来增加索引。当 freq 指定为“infer”时,可以推断出 freq,只要索引中设置了 freq 或 inferred_freq 属性。
- Parameters:
- 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}, default None
移动方向。对于 Series,此参数未使用,默认为 0。
- fill_valueobject, optional
用于新引入的缺失值标量。默认值取决于 self 的 dtype。对于数值数据,使用
np.nan。对于 datetime、timedelta 或 period 数据等,使用NaT。对于扩展 dtype,使用self.dtype.na_value。- suffixbool, default False
如果 str 和 periods 是一个可迭代对象,则对于每个移位的列名,它会添加到列名之后和移位值之前。
- Returns:
- Series/DataFrame
输入对象的副本,已移位。
参见
Index.shiftIndex 的移位值。
DatetimeIndex.shiftDatetimeIndex 的移位值。
PeriodIndex.shiftPeriodIndex 的移位值。
Examples
>>> df = pd.DataFrame({"Col1": [10, 20, 15, 30, 45], ... "Col2": [13, 23, 18, 33, 48], ... "Col3": [17, 27, 22, 37, 52]}, ... 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