Cyclic shift of a pandas series

前端 未结 3 1511
我在风中等你
我在风中等你 2021-02-19 02:15

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?

相关标签:
3条回答
  • 2021-02-19 02:55

    Here's a slight modification of @EdChum 's great answer, which I find more useful in situations where I want to avoid an assignment:

    pandas.DataFrame(np.roll(df.values, 1), index=df.index)
    

    or for Series:

    pandas.Series(np.roll(ser.values, 1), index=ser.index)
    
    0 讨论(0)
  • 2021-02-19 03:10

    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
    
    0 讨论(0)
  • 2021-02-19 03:11

    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
    
    0 讨论(0)
提交回复
热议问题