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

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

    Here's an answer that actually examines the parts of the array you're interested in, and doesn't waste time constructing a mask the size of the whole array. There's a Python-level loop, but it's short, with iterations proportional to the number of dimensions instead of the array's size.

    def all_borders_zero(array):
        if not array.ndim:
            raise ValueError("0-dimensional arrays not supported")
        for dim in range(array.ndim):
            view = numpy.moveaxis(array, dim, 0)
            if not (view[0] == 0).all():
                return False
            if not (view[-1] == 0).all():
                return False
        return True
    

提交回复
热议问题