[英]How to get rid of numpy “bands” containing zeros
我有一個 3D numpy 數組,它表示給定時間步數的 2D 圖像。 軸的組織如下:(時間步長,x_dimension,y_dimension)。 我想通過時間步長 go 並刪除僅包含零值的“帶”。 我有一個工作解決方案,可以循環遍歷數組,但想實現一種更 Pythonic 的方法。 但是,我對尺寸感到困惑,看不到將解決方案應用於軸。 我目前使用循環的方法:
print(arr.shape)
> (20, 512, 512)
我有一個 512x512 像素的圖像,有 20 個波段。
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, 512)
我歡迎在沒有循環的情況下應用這種方法的任何幫助。
您可以對all
使用 axis 關鍵字:
indices_zeros = (arr == 0).all((1, 2))
new_array = arr[~indices_zero]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.