Shift elements in a numpy array

前端 未结 8 1717
萌比男神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:06

    Not numpy but scipy provides exactly the shift functionality you want,

    import numpy as np
    from scipy.ndimage.interpolation import shift
    
    xs = np.array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.])
    
    shift(xs, 3, cval=np.NaN)
    

    where default is to bring in a constant value from outside the array with value cval, set here to nan. This gives the desired output,

    array([ nan, nan, nan, 0., 1., 2., 3., 4., 5., 6.])
    

    and the negative shift works similarly,

    shift(xs, -3, cval=np.NaN)
    

    Provides output

    array([  3.,   4.,   5.,   6.,   7.,   8.,   9.,  nan,  nan,  nan])
    

提交回复
热议问题