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

前端 未结 5 1584
青春惊慌失措
青春惊慌失措 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:16

    I reshaped the array and then iterated through it. Unfortunately, my answer assumes you have at least three dimensions and will error out for normal matrices, you would have to add a special clause for 1 & 2 dimensional shaped arrays. In addition, this will be slow so there are likely better solutions.

    x = np.array(
            [
                [
                    [0 , 1, 1, 0],
                    [0 , 2, 3, 0],
                    [0 , 4, 5, 0]
                ],
                [
                    [0 , 6, 7, 0],
                    [0 , 7, 8, 0],
                    [0 , 9, 5, 0]
                ]
            ])
    
    xx = np.array(
            [
                [
                    [0 , 0, 0, 0],
                    [0 , 2, 3, 0],
                    [0 , 0, 0, 0]
                ],
                [
                    [0 , 0, 0, 0],
                    [0 , 7, 8, 0],
                    [0 , 0, 0, 0]
                ]
            ])
    
    def check_edges(x):
    
        idx = x.shape
        chunk = np.prod(idx[:-2])
        x = x.reshape((chunk*idx[-2], idx[-1]))
        for block in range(chunk):
            z = x[block*idx[-2]:(block+1)*idx[-2], :]
            if not np.all(z[:, 0] == 0):
                return False
            if not np.all(z[:, -1] == 0):
                return False
            if not np.all(z[0, :] == 0):
                return False
            if not np.all(z[-1, :] == 0):
                return False
    
        return True
    

    Which will produce

    >>> False
    >>> True
    

    Basically I stack all the dimensions on top of each other and then look through them to check their edges.

提交回复
热议问题