如何摆脱包含零的numpy“带”

问题描述

我有一个3D numpy数组,它以给定的时间步长表示2D图像。轴的组织方式如下:(时间步,x_dimension,y_dimension)。我想遍历时间步长并删除仅包含零值的“带”。我有一个遍历数组的有效解决方案,但想实现一种更pythonic的方法。但是,我对尺寸感到困惑,看不到将解决方案应用于轴。 我当前的循环方法

print(arr.shape)

> (20,512,512)

我有一个20条带的512x512像素图像。

indices_zeros = []
# Loop through the first axis and find index of bands containing only zeros
for i in range(arr.shape[0]):
    if not arr[i,:,:].any():
        indices_zeros.append(i)

# Remove 0-axis elements based on prevIoUs step
new_array = np.delete(arr,indices_zeros,axis=0)
new_array.shape

> (7,512)

我欢迎在不循环的情况下应用此方法的任何帮助。

解决方法

您可以将axis关键字用于all

indices_zeros = (arr == 0).all((1,2))
new_array = arr[~indices_zero]