Transferred from: https://sanwen8.cn/p/2241oUa.html
The shift function is the operation to move the data, assuming that there is now a dataframe data df, as follows:
Index |
value1 |
A |
0 |
B |
1 |
C |
2 |
D |
3 |
Then, if you execute the following code:
df.shift()
It will become as follows:
Index |
value1 |
A |
NaN |
B |
0 |
C |
1 |
D |
2 |
Look at the function prototype:
DataFrame.shift(periods=1, freq=None, axis=0)
Parameters
- Periods: type int, indicating the amplitude of the move, can be positive, or negative, the default value is to move one time, note that the movement is data, and the index is not moved, after the move does not have a corresponding value, the assignment is Nan.
Execute the following code:
df.shift(2)
You will get:
Index |
value1 |
A |
NaN |
B |
NaN |
C |
0 |
D |
1 |
Perform:
df.shift(-1)
Will get:
Index |
value1 |
A |
1 |
B |
2 |
C |
3 |
D |
NaN |
- Freq:dateoffset, Timedelta, or time rule string, optional parameter, the default value is None, applies only to time series, if this parameter exists, it will be moved by the parameter value, and the data value has not changed. For example now there are df1 as follows:
Index |
value1 |
2016-06-01 |
0 |
2016-06-02 |
1 |
2016-06-03 |
2 |
2016-06-04 |
3 |
Perform:
df1.shift(periods=1,freq=datetime.timedelta(1))
Will get:
Index | Value1
--|--
2016-06-02 | 0
2016-06-03 | 1
2016-06-04 | 2
2016-06-05 | 3
- axis:{0, 1, ' Index ', ' columns ', indicates the direction of the move, if it is 0 or ' index ' means move up or down, if it is 1 or ' columns ', it will move left and right.
The shift of pandas common functions