Pandas Shift函數(shù)基礎(chǔ)
在使用Pandas的過程中,有時會遇到shift函數(shù),今天就一起來徹底學(xué)習(xí)下。先來看看幫助文檔是怎么說的:
>>> 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該函數(shù)主要的功能就是使數(shù)據(jù)框中的數(shù)據(jù)移動,若freq=None時,根據(jù)axis的設(shè)置,行索引數(shù)據(jù)保持不變,列索引數(shù)據(jù)可以在行上上下移動或在列上左右移動;若行索引為時間序列,則可以設(shè)置freq參數(shù),根據(jù)periods和freq參數(shù)值組合,使行索引每次發(fā)生periods*freq偏移量滾動,列索引數(shù)據(jù)不會移動。
參數(shù)詳解:
period:表示移動的幅度,可以是正數(shù),也可以是負(fù)數(shù),默認(rèn)值是1,1就表示移動一次,注意這里移動的都是數(shù)據(jù),而索引是不移動的,移動之后沒有對應(yīng)值的,就賦值為NaN。 freq: DateOffset, timedelta, or time rule string,可選參數(shù),默認(rèn)值為None,只適用于時間序列,如果這個參數(shù)存在,那么會按照參數(shù)值移動時間索引,而數(shù)據(jù)值沒有發(fā)生變化。 axis: {0, 1, ‘index', ‘columns'},表示移動的方向,如果是0或者'index'表示上下移動,如果是1或者'columns',則會左右移動。先來看一下一些簡單的示例:
1、非時間索引下period的設(shè)置
假設(shè)存在一個DataFrame數(shù)據(jù)df:
index value1A 0B 1C 2D 3
如果執(zhí)行以下代碼 df.shift() 就會變成如下:
index value1A NaNB 0C 1D 2
執(zhí)行 df.shift(2) 就會得到:
index value1A NaNB NaNC 0D 1
執(zhí)行 df.shift(-1) 會得到:
index value1A 1B 2C 3D NaN
注意,shift移動的是整個數(shù)據(jù),如果df有如下多列數(shù)據(jù):
AA BB CC DDa 0 1 2 3b 4 5 6 7c 8 9 10 11d 12 13 14 15
執(zhí)行 df.shift(2) 的數(shù)據(jù)為:
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中的某一列數(shù)據(jù),則需要這樣操作: df['DD']= df['DD'].shift(1)
執(zhí)行后的數(shù)據(jù)為:
AA BB CC DDa 0 1 2 NaNb 4 5 6 NaNc 8 9 10 11d 12 13 14 15
新聞熱點
疑難解答