Pandas series cyclic shift

I use the shift method for a series of data in pandas   (documentation) .

Is it possible to make a cyclic shift, i.e. will the first value become the last value in one step?

>>> input
Out[20]: 
5     0.995232
15    0.999794
25    1.006853
35    0.997781
45    0.981553
Name: vRatio, dtype: float64

>>> input.shift()
Out[21]: 
5          NaN
15    0.995232
25    0.999794
35    1.006853
45    0.997781
Name: vRatio, dtype: float64

desired result:

Out[21]: 
5     0.981553
15    0.995232
25    0.999794
35    1.006853
45    0.997781
Name: vRatio, dtype: float64
+4
source share
2 answers

You can use np.rollto rotate the index values ​​and pass this value as reindex:

In [23]:
df.reindex(index=np.roll(df.index,1))

Out[23]:
         vRatio
index          
45     0.981553
5      0.995232
15     0.999794
25     1.006853
35     0.997781

If you want to keep your index, you can simply overwrite the values ​​again using np.roll:

In [25]:
df['vRatio'] = np.roll(df['vRatio'],1)
df

Out[25]:
         vRatio
index          
5      0.981553
15     0.995232
25     0.999794
35     1.006853
45     0.997781
+3
source

To do this without using one step:

>>> output = input.shift()
>>> output.loc[output.index.min()] = input.loc[input.index.max()]
>>> output
Out[32]: 
5     0.981553
15    0.995232
25    0.999794
35    1.006853
45    0.997781
Name: vRatio, dtype: float64
0
source

Source: https://habr.com/ru/post/1599071/


All Articles