通過?pandas.DataFrame.shift命令查看幫助文檔
Signature: pandas.DataFrame.shift(self, periods=1, freq=None, axis=0)
Docstring:
Shift index by desired number of periods with an optional time freq
該函數(shù)主要的功能就是使數(shù)據(jù)框中的數(shù)據(jù)移動,若freq=None時(shí)姿搜,根據(jù)axis的設(shè)置,行索引數(shù)據(jù)保持不變庄蹋,列索引數(shù)據(jù)可以在行上上下移動或在列上左右移動夺鲜;若行索引為時(shí)間序列,則可以設(shè)置freq參數(shù),根據(jù)periods和freq參數(shù)值組合迁央,使行索引每次發(fā)生periods*freq偏移量滾動,列索引數(shù)據(jù)不會移動
① 對于DataFrame的行索引是日期型滥崩,行索引發(fā)生移動岖圈,列索引數(shù)據(jù)不變
In [2]: import pandas as pd
...: import numpy as np
...: df = pd.DataFrame(np.arange(24).reshape(6,4),index=pd.date_range(start=
...: '20170101',periods=6),columns=['A','B','C','D'])
...: df
...:
Out[2]:
A B C D
2017-01-01 0 1 2 3
2017-01-02 4 5 6 7
2017-01-03 8 9 10 11
2017-01-04 12 13 14 15
2017-01-05 16 17 18 19
2017-01-06 20 21 22 23
In [3]: df.shift(2,axis=0,freq='2D')
Out[3]:
A B C D
2017-01-05 0 1 2 3
2017-01-06 4 5 6 7
2017-01-07 8 9 10 11
2017-01-08 12 13 14 15
2017-01-09 16 17 18 19
2017-01-10 20 21 22 23
In [4]: df.shift(2,axis=1,freq='2D')
Out[4]:
A B C D
2017-01-05 0 1 2 3
2017-01-06 4 5 6 7
2017-01-07 8 9 10 11
2017-01-08 12 13 14 15
2017-01-09 16 17 18 19
2017-01-10 20 21 22 23
In [5]: df.shift(2,freq='2D')
Out[5]:
A B C D
2017-01-05 0 1 2 3
2017-01-06 4 5 6 7
2017-01-07 8 9 10 11
2017-01-08 12 13 14 15
2017-01-09 16 17 18 19
2017-01-10 20 21 22 23
通過?pandas.DataFrame.diff命令查看幫助文檔,發(fā)現(xiàn)和shift函數(shù)形式一樣
Signature: pd.DataFrame.diff(self, periods=1, axis=0)
Docstring:
1st discrete difference of object
下面看看diff函數(shù)和shift函數(shù)之間的關(guān)系
In [13]: df.diff(periods=2,axis=0)
Out[13]:
A B C D
r1 NaN NaN NaN NaN
r2 NaN NaN NaN NaN
r3 8.0 8.0 8.0 8.0
r4 8.0 8.0 8.0 8.0
r5 8.0 8.0 8.0 8.0
r6 8.0 8.0 8.0 8.0
In [14]: df -df.diff(periods=2,axis=0)
Out[14]:
A B C D
r1 NaN NaN NaN NaN
r2 NaN NaN NaN NaN
r3 0.0 1.0 2.0 3.0
r4 4.0 5.0 6.0 7.0
r5 8.0 9.0 10.0 11.0
r6 12.0 13.0 14.0 15.0
In [15]: df.shift(periods=2,axis=0)
Out[15]:
A B C D
r1 NaN NaN NaN NaN
r2 NaN NaN NaN NaN
r3 0.0 1.0 2.0 3.0
r4 4.0 5.0 6.0 7.0
r5 8.0 9.0 10.0 11.0
r6 12.0 13.0 14.0 15.0