【python】pandas庫常用函數之shift詳解__函數

來源:互聯網
上載者:User
- 首先看一下 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.