pandas 系列的循环移位 [英] Cyclic shift of a pandas series
本文介绍了 pandas 系列的循环移位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在对 Pandas 中的数据系列使用 shift 方法(文档).
是否可以在一个步骤中进行循环移位,即第一个值变成最后一个值?
<预><代码>>>>输入出[20]:5 0.99523215 0.99979425 1.00685335 0.99778145 0.981553名称:vRatio,数据类型:float64>>>input.shift()出[21]:5 纳米15 0.99523225 0.99979435 1.00685345 0.997781名称:vRatio,数据类型:float64所需的输出:
输出[21]:5 0.98155315 0.99523225 0.99979435 1.00685345 0.997781名称:vRatio,数据类型:float64
解决方案
您可以使用 np.roll
循环索引值并将其作为值传递给 reindex
:
在 [23] 中:df.reindex(index=np.roll(df.index,1))出[23]:比率指数45 0.9815535 0.99523215 0.99979425 1.00685335 0.997781
如果您想保留索引,则可以使用 np.roll
再次覆盖这些值:
在 [25] 中:df['vRatio'] = np.roll(df['vRatio'],1)df出[25]:比率指数5 0.98155315 0.99523225 0.99979435 1.00685345 0.997781
I am using the shift method for a data series in pandas (documentation).
Is it possible do a cyclic shift, i.e. 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
:
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
:
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
这篇关于 pandas 系列的循环移位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文