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

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

    maybe the ellipsis operator is what you are looking for, which will work for many dimensions:

    import numpy as np
    
    # data
    x = np.random.rand(2, 5, 5)
    x[..., 0:, 0] = 0
    x[..., 0, 0:] = 0
    x[..., 0:, -1] = 0
    x[..., -1, 0:] = 0
    
    test = np.all(
        [
            np.all(x[..., 0:, 0] == 0),
            np.all(x[..., 0, 0:] == 0),
            np.all(x[..., 0:, -1] == 0),
            np.all(x[..., -1, 0:] == 0),
        ]
    )
    
    print(test)
    

提交回复
热议问题