Changing values on the edges of an array in NumPy

后端 未结 3 793
孤独总比滥情好
孤独总比滥情好 2021-01-20 07:29

I am to create an array using only NumPy tools. There it is:

[[2 2 2 2 2]
 [2 1 1 1 2]
 [2 1 1 1 2]
 [2 1 1 1 2]
 [2 2 2 2 2]]

That is my

3条回答
  •  我在风中等你
    2021-01-20 08:13

    Approach #1

    Initialize with 2s (edge values) and assign 1s in middle portion -

    x = 2*np.ones((5, 5), dtype = int)
    x[1:-1,1:-1] = 1
    

    Approach #2

    Another short way -

    x = np.ones((5, 5), dtype = int)
    x[:,[0,-1]] = x[[0,-1]] = 2
    

    Approach #3

    One-liner with 2D convolution -

    In [302]: from scipy.signal import convolve2d
    
    In [303]: (convolve2d(np.ones((5,5)), np.ones((3,3)),'same')<9)+1
    Out[303]: 
    array([[2, 2, 2, 2, 2],
           [2, 1, 1, 1, 2],
           [2, 1, 1, 1, 2],
           [2, 1, 1, 1, 2],
           [2, 2, 2, 2, 2]])
    

提交回复
热议问题