python numpy roll with padding

后端 未结 7 1031
孤街浪徒
孤街浪徒 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 10:02

    A bit late, but feels like a quick way to do what you want in one line. Perhaps would work best if wrapped inside a smart function (example below provided just for horizontal axis):

    import numpy
    
    a = numpy.arange(1,10).reshape(3,3)  # an example 2D array
    
    print a
    
    [[1 2 3]
     [4 5 6]
     [7 8 9]]
    
    shift = 1
    a = numpy.hstack((numpy.zeros((a.shape[0], shift)), a[:,:-shift]))
    
    print a
    
    [[0 1 2]
     [0 4 5]
     [0 7 8]]
    

提交回复
热议问题