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偏移量滾動,列索引數據不會移動。
參數詳解:
先來看一下一些簡單的示例:
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
2、時間索引下freq 參數設置
假設存在如下DataFrame的df:
df = pd.DataFrame(np.arange(16).reshape(4,4),columns=['AA','BB','CC','DD'],index =pd.date_range('2012-06-01','2012-06-04'))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 15
執行 df.shift(freq=datetime.timedelta(1)) 后:
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 15
執行 df.shift(freq=datetime.timedelta(-2)) 后:
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
可以看到索引直接變了。
3、axis軸向設置
df = pd.DataFrame(np.arange(16).reshape(4,4),columns=['AA','BB','CC','DD'],index =['a','b','c','d']) dfOut[1]: 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[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#當axis=1,沿水平方向進行移動,正數向右移,負數向左移df.shift(2,axis = 1)Out[3]: 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[4]: 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
pandas 中上下兩行相減(隔行相減) -- shift函數的使用
最近使用pandas處理數據,需求是想相鄰兩行上下相減,查API發現shift函數,很靈活,。你也可以隔任意行相減。
p['xx_1'] = p["xx"].shift(1)
上面得到的就是xx字段向下移動一行的結果,和之前相比向下移動一行,你可以設置為任意行,也可是向上向下
p['xx'] - p["xx_1"]
這就是前后兩行的差值,很方便,Pandas很強大
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。
新聞熱點
疑難解答