Python 级数的循环移位
我正在对熊猫中的数据系列使用shift方法 是否可以在一个步骤中进行循环移位,即第一个值变为最后一个值Python 级数的循环移位,python,pandas,Python,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.995
>>> 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
要在不使用单个步骤的情况下执行此操作,请执行以下操作:
>>> 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
可以使用循环索引值,并将其作为值传递给:
如果要保留索引,可以使用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
下面是对@EdChum的伟大答案的一点修改,我发现在我想避免任务的情况下,这一点更有用:
pandas.DataFrame(np.roll(df.values, 1), index=df.index)
或对于系列:
pandas.Series(np.roll(ser.values, 1), index=ser.index)
pandas.Series(np.roll(ser.values, 1), index=ser.index)