Shift elements in a numpy array

前端 未结 8 1727
萌比男神i
萌比男神i 2020-12-01 00:54

Following-up from this question years ago, is there a canonical \"shift\" function in numpy? I don\'t see anything from the documentation.

Here\'s a simple version o

8条回答
  •  囚心锁ツ
    2020-12-01 01:07

    You can also do this with Pandas:

    Using a 2356-long array:

    import numpy as np
    
    xs = np.array([...])
    

    Using scipy:

    from scipy.ndimage.interpolation import shift
    
    %timeit shift(xs, 1, cval=np.nan)
    # 956 µs ± 77.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    

    Using Pandas:

    import pandas as pd
    
    %timeit pd.Series(xs).shift(1).values
    # 377 µs ± 9.42 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    

    In this example, using Pandas was about ~8 times faster than Scipy

提交回复
热议问题