Pandas Shift函數基礎
在使用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
該函數主要的功能就是使數據框中的數據移動,若freq=None時,根據axis的設置,行索引數據保持不變,列索引數據可以在行上上下移動或在列上左右移動;若行索引為時間序列,則可以設置freq參數,根據periods和freq參數值組合,使行索引每次發生periods*freq偏移量滾動,列索引數據不會移動。
參數詳解:
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 value1A 0B 1C 2D 3
如果執行以下代碼 df.shift() 就會變成如下:
index value1A NaNB 0C 1D 2
執行 df.shift(2) 就會得到:
index value1A NaNB NaNC 0D 1
執行 df.shift(-1) 會得到:
index value1A 1B 2C 3D NaN
注意,shift移動的是整個數據,如果df有如下多列數據:
AA BB CC DDa 0 1 2 3b 4 5 6 7c 8 9 10 11d 12 13 14 15
執行 df.shift(2) 的數據為:
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
如果只想移動df中的某一列數據,則需要這樣操作: df['DD']= df['DD'].shift(1)
執行后的數據為:
AA BB CC DDa 0 1 2 NaNb 4 5 6 NaNc 8 9 10 11d 12 13 14 15
新聞熱點
疑難解答