gpt4 book ai didi

python - Pandas 系列的循环移位

转载 作者:太空狗 更新时间:2023-10-29 21:45:59 26 4
gpt4 key购买 nike

我正在对 pandas 中的数据系列使用 shift 方法 (documentation) .

是否可以在一个步骤中进行循环移位,即第一个值成为最后一个值?

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

最佳答案

您可以使用 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

关于python - Pandas 系列的循环移位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31561412/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com