Check if all sides of a multidimensional numpy array are arrays of zeros

前端 未结 5 1496
青春惊慌失措
青春惊慌失措 2021-02-13 16:55

An n-dimensional array has 2n sides (a 1-dimensional array has 2 endpoints; a 2-dimensional array has 4 sides or edges; a 3-dimensional array has 6 2-dimensional faces; a 4-dime

5条回答
  •  野的像风
    2021-02-13 17:18

    You can make use of slice and boolean masking to get the job done:

    def get_borders(arr):
        s=tuple(slice(1,i-1) for i in a.shape)
        mask = np.ones(arr.shape, dtype=bool)
        mask[s] = False
        return(arr[mask])
    

    This function first shapes the "core" of the array into the tuple s, and then builds a mask that shows True only for the bordering points. Boolean indexing then delivers the border points.

    Working example:

    a = np.arange(16).reshape((4,4))
    
    print(a)
    array([[ 0,  1,  2,  3],
           [ 4,  5,  6,  7],
           [ 8,  9, 10, 11],
           [12, 13, 14, 15]])
    
    borders = get_borders(a)
    print(borders)
    array([ 0,  1,  2,  3,  4,  7,  8, 11, 12, 13, 14, 15])
    

    Then, np.all(borders==0) will give you the desired information.


    Note: this breaks for one-dimensional arrays, though I consider those an edge case. You're probably better off just checking the two points in question there

提交回复
热议问题