pandas DataFrame.shift()

The pandas DataFrame.shift() function can move the data by the specified number of bits

The period parameter specifies the step of the movement, which can be positive or negative. axis specifies the axis of the movement, 1 is the row, 0 is the column, and the default is 0.

import pandas as pd
data1 = pd.DataFrame({
    'a': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
    'b': [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
})
print data1
   a  b
0  0  9
1  1  8
2  2  7
3  3  6
4  4  5
5  5  4
6  6  3
7  7  2
8  8  1
9  9  0

If you want the data of a and b to move down one place:
 

data2 = data1.shift(axis=0)
print data2
    a    b
0  NaN  NaN
1  0.0  9.0
2  1.0  8.0
3  2.0  7.0
4  3.0  6.0
5  4.0  5.0
6  5.0  4.0
7  6.0  3.0
8  7.0  2.0
9  8.0  1.0

If you move one place to the right on the line:

data3 = data1.shift(axis=1)
print data3
   a    b
0 NaN  0.0
1 NaN  1.0
2 NaN  2.0
3 NaN  3.0
4 NaN  4.0
5 NaN  5.0
6 NaN  6.0
7 NaN  7.0
8 NaN  8.0
9 NaN  9.0

 If you want to move up or left, you can specify (periods=-1):

data4 = data1.shift(periods=-1, axis=0)
print data4
    a    b
0  1.0  8.0
1  2.0  7.0
2  3.0  6.0
3  4.0  5.0
4  5.0  4.0
5  6.0  3.0
6  7.0  2.0
7  8.0  1.0
8  9.0  0.0
9  NaN  NaN

参考 https://www.cnblogs.com/liulangmao/p/9301032.html

Guess you like

Origin blog.csdn.net/weixin_43217427/article/details/109456279