Shear a numpy array

后端 未结 5 1663
执念已碎
执念已碎 2020-12-18 00:40

I\'d like to \'shear\' a numpy array. I\'m not sure I\'m using the term \'shear\' correctly; by shear, I mean something like:

Shift the first column by 0 places

5条回答
  •  温柔的废话
    2020-12-18 01:17

    This can be done using a trick described in this answer by Joe Kington:

    from numpy.lib.stride_tricks import as_strided
    a = numpy.array([[11, 12, 13],
                     [17, 18, 19],
                     [35, 36, 37]])
    shift_axis = 0
    increase_axis = 1
    b = numpy.vstack((a, a))
    strides = list(b.strides)
    strides[increase_axis] -= strides[shift_axis]
    strides = (b.strides[0], b.strides[1] - b.strides[0])
    as_strided(b, shape=b.shape, strides=strides)[a.shape[0]:]
    # array([[11, 36, 19],
    #        [17, 12, 37],
    #        [35, 18, 13]])
    

    To get "clip" instead of "roll", use

    b = numpy.vstack((numpy.zeros(a.shape, int), a))
    

    This is probably the most efficient way of doing it, since it does not use any Python loop at all.

提交回复
热议问题