How to get all array edges?

前端 未结 5 1277
攒了一身酷
攒了一身酷 2021-01-05 08:17

I have a n x n array, and want to receive its outline values. For example,

[4,5,6,7]

[2,2,6,3]

5条回答
  •  迷失自我
    2021-01-05 08:44

    It's probably slower than the alternatives mentioned in the other answers because it's creating a mask (which was my use-case then) it can be used in your case:

    def mask_borders(arr, num=1):
        mask = np.zeros(arr.shape, bool)
        for dim in range(arr.ndim):
            mask[tuple(slice(0, num) if idx == dim else slice(None) for idx in range(arr.ndim))] = True  
            mask[tuple(slice(-num, None) if idx == dim else slice(None) for idx in range(arr.ndim))] = True  
        return mask
    

    As already said this creates and returns a mask where the borders are masked (True):

    >>> mask_borders(np.ones((5,5)))
    array([[ True,  True,  True,  True,  True],
           [ True, False, False, False,  True],
           [ True, False, False, False,  True],
           [ True, False, False, False,  True],
           [ True,  True,  True,  True,  True]], dtype=bool)
    
    >>> # Besides supporting arbitary dimensional input it can mask multiple border rows/cols
    >>> mask_borders(np.ones((5,5)), 2)
    array([[ True,  True,  True,  True,  True],
           [ True,  True,  True,  True,  True],
           [ True,  True, False,  True,  True],
           [ True,  True,  True,  True,  True],
           [ True,  True,  True,  True,  True]], dtype=bool)
    

    To get the "border" values this needs to be applied with boolean indexing to your array:

    >>> arr = np.array([[4,5,6,7], [2,2,6,3], [4,4,9,4], [8,1,6,1]])
    
    >>> arr[mask_borders(arr)]
    array([4, 5, 6, 7, 2, 3, 4, 4, 8, 1, 6, 1])
    

提交回复
热议问题