- 首先看一下 df.shift(periods=1, freq=None, axis=0) 的源碼解釋:
df.shift?Signature: df.shift(periods=1, freq=None, axis=0)Docstring:Shift index by desired number of periods with an optional time freqParameters----------periods : int Number of periods to move, can be positive or negativefreq : 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 datais not realigned. That is, use freq if you would like to extend theindex when shifting and preserve the original data.
- 註解:
period:表示移動的幅度,可以是正數,也可以是負數,預設值是1,1就表示移動一次,注意這裡移動的都是資料,而索引是不移動的,移動之後沒有對應值的,就賦值為NaN。
freq: DateOffset, timedelta, or time rule string,選擇性參數,預設值為None,只適用於時間序列,如果這個參數存在,那麼會按照參數值移動時間索引,而資料值沒有發生變化。 axis: 軸向。 - 執行個體
1、設定 period 與 axis
df = pd.DataFrame(np.arange(16).reshape(4,4),columns=['AA','BB','CC','DD'],index =['a','b','c','d'])dfOut[14]: AA BB CC DDa 0 1 2 3b 4 5 6 7c 8 9 10 11d 12 13 14 15#當period為正時,預設是axis = 0軸的設定,向下移動df.shift(2)Out[15]: AA BB CC DDa NaN NaN NaN NaNb NaN NaN NaN NaNc 0.0 1.0 2.0 3.0d 4.0 5.0 6.0 7.0#當axis=1,沿水平方向進行移動,正數向右移,負數向左移df.shift(2,axis = 1)Out[16]: AA BB CC DDa NaN NaN 0.0 1.0b NaN NaN 4.0 5.0c NaN NaN 8.0 9.0d NaN NaN 12.0 13.0#當period為負時,預設是axis = 0軸的設定,向上移動df.shift(-1)Out[17]: AA BB CC DDa 4.0 5.0 6.0 7.0b 8.0 9.0 10.0 11.0c 12.0 13.0 14.0 15.0d NaN NaN NaN NaN
2、freq 參數執行個體
df = pd.DataFrame(np.arange(16).reshape(4,4),columns=['AA','BB','CC','DD'],index =pd.date_range('6/1/2012','6/4/2012'))dfOut[38]: AA BB CC DD2012-06-01 0 1 2 32012-06-02 4 5 6 72012-06-03 8 9 10 112012-06-04 12 13 14 15df.shift(freq=datetime.timedelta(1))Out[39]: AA BB CC DD2012-06-02 0 1 2 32012-06-03 4 5 6 72012-06-04 8 9 10 112012-06-05 12 13 14 15df.shift(freq=datetime.timedelta(-2))Out[40]: AA BB CC DD2012-05-30 0 1 2 32012-05-31 4 5 6 72012-06-01 8 9 10 112012-06-02 12 13 14 15