[英]Cyclic shift of a pandas series
I am using the shift method for a data series in pandas (documentation) .我正在对 pandas (documentation) 中的数据系列使用 shift 方法。
Is it possible do a cyclic shift, ie 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 output:所需的输出:
Out[21]:
5 0.981553
15 0.995232
25 0.999794
35 1.006853
45 0.997781
Name: vRatio, dtype: float64
You can use np.roll
to cycle the index values and pass this as the values to reindex
:您可以使用
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
If you want to preserve your index then you can just overwrite the values again using np.roll
:如果你想保留你的索引,那么你可以使用
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
Here's a slight modification of @EdChum 's great answer, which I find more useful in situations where I want to avoid an assignment:这是@EdChum 的好答案的轻微修改,我发现在我想避免分配的情况下更有用:
pandas.DataFrame(np.roll(df.values, 1), index=df.index)
or for Series:或系列:
pandas.Series(np.roll(ser.values, 1), index=ser.index)
To do this without using a single 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.