python numpy roll with padding

后端 未结 7 1013
孤街浪徒
孤街浪徒 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:48

    Elaborating on the answer by Hooked (since it took me a few minutes to understand it)

    The code below first pads a certain amount of zeros in the up, down, left and right margins and then selects the original matrix inside the padded one. A perfectly useless code, but good for understanding np.pad.

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

    now to make an upwards shift of 2 combined with a rightwards shift of 1 position one should do

    print np.pad(x,((0,2),(1,0)), mode='constant')[2:0,0:-1]
    

提交回复
热议问题