Pandas系列的循环移位

21

我在pandas中使用shift方法对数据序列进行操作,具体说明请参见文档

是否可以进行循环移位,即将第一个值变为最后一个值,只需一步操作?

>>> 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

期望输出:

Out[21]: 
5     0.981553
15    0.995232
25    0.999794
35    1.006853
45    0.997781
Name: vRatio, dtype: float64
3个回答

29

你可以使用np.roll函数来循环索引值,并将其作为参数传递给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

如果您想保留索引,则可以使用 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
这是对@EdChum的优秀答案进行的轻微修改,我发现在我想避免分配的情况下更有用:
pandas.DataFrame(np.roll(df.values, 1), index=df.index)

或者对于系列:

pandas.Series(np.roll(ser.values, 1), index=ser.index)

0

不使用任何步骤来完成这个任务:

>>> 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接