Pandas Shift函数基础
官方帮助文档如下:
>>> import pandas
>>> help(pandas.DataFrame.shift)
Help on function shift in module pandas.core.frame:
shift(self, periods=1, freq=None, axis=0)
Shift index by desired number of periods with an optional time freq
Parameters
----------
periods : int
Number of periods to move, can be positive or negative
freq : DateOffset, timedelta, or time rule string, optional
Increment to use from the tseries module or time rule (e.g. 'EOM').
See Notes.
axis : {
0 or 'index', 1 or 'columns'}
Notes
-----
If freq is specified then the index values are shifted but the data
is not realigned. That is, use freq if you would like to extend the
index when shifting and preserve the original data.
Returns
-------
shifted : DataFrame
参数解释:
- period:表示移动的幅度,可以是正数,也可以是负数,默认值是1,1就表示移动一次,注意这里移动的都是数据,而索引是不移动的,移动之后没有对应值的,就赋值为NaN。
- freq: DateOffset, timedelta, or time rule string,可选参数,默认值为None,只适用于时间序列,如果这个参数存在,那么会按照参数值移动时间索引,而数据值没有发生变化。
- axis: {0, 1, ‘index’, ‘columns’},表示移动的方向,如果是0或者’index’表示上下移动,如果是1或者’columns’,则会左右移动。
先来看一下一些简单的示例
1、非时间索引下period的设置
假设存在一个DataFrame数据df:
index value1
A 0
B 1
C 2
D 3
如果执行以下代码 df.shift() 就会变成如下:
index value1
A NaN
B 0
C 1
D 2