python numpy roll with padding

后端 未结 7 1028
孤街浪徒
孤街浪徒 2020-12-16 09:17

I\'d like to roll a 2D numpy in python, except that I\'d like pad the ends with zeros rather than roll the data as if its periodic.

Specifically, the following code<

7条回答
  •  醉话见心
    2020-12-16 09:53

    There is a new numpy function in version 1.7.0 numpy.pad that can do this in one-line. Pad seems to be quite powerful and can do much more than a simple "roll". The tuple ((0,0),(1,0)) used in this answer indicates the "side" of the matrix which to pad.

    import numpy as np
    x = np.array([[1, 2, 3],[4, 5, 6]])
    
    print np.pad(x,((0,0),(1,0)), mode='constant')[:, :-1]
    

    Giving

    [[0 1 2]
     [0 4 5]]
    

提交回复
热议问题