How to delete zero-values rows in a multi-dimensional numpy array?

Viewed 72

Array is as follows - how can I delete the all zeros rows?

a = np.array([[[0.7176471  ,0.45490196 ,1.         ,1.        ],
  [0.6509804  ,0.654902   ,0.2509804  ,1.        ],
  [0.         ,0.         ,0.         ,0.        ],  
  [0.         ,0.         ,0.         ,0.        ]],
 [[0.58431375 ,0.44705883 ,0.24705882 ,1.        ],
  [0.41960785 ,0.3254902  ,1.         ,1.        ],
  [0.         ,0.         ,0.         ,0.        ],
  [0.         ,0.         ,0.         ,0.        ]],
 [[0.23137255 ,0.3137255  ,0.5254902  ,1.        ],
  [0.70980394 ,0.7411765  ,0.5568628  ,1.        ],
  [0.         ,0.         ,0.         ,0.        ],
  [0.         ,0.         ,0.         ,0.        ]]])
1 Answers

Here you go:

res = np.reshape(a[a[:,:, -1] != 0], (a.shape[0],-1,a.shape[-1]))

Example:

a = np.array([[[0.7176471  ,0.45490196 ,1.         ,1.        ],
  [0.6509804  ,0.654902   ,0.2509804  ,1.        ],
  [0.         ,0.         ,0.         ,0.        ],  
  [0.         ,0.         ,0.         ,0.        ]],
 [[0.58431375 ,0.44705883 ,0.24705882 ,1.        ],
  [0.41960785 ,0.3254902  ,1.         ,1.        ],
  [0.         ,0.         ,0.         ,0.        ],
  [0.         ,0.         ,0.         ,0.        ]],
 [[0.23137255 ,0.3137255  ,0.5254902  ,1.        ],
  [0.70980394 ,0.7411765  ,0.5568628  ,1.        ],
  [0.         ,0.         ,0.         ,0.        ],
  [0.         ,0.         ,0.         ,0.        ]]])

res = np.reshape(a[a[:,:, -1] != 0], (a.shape[0],-1,a.shape[-1]))

Output:

array([[[0.7176471 , 0.45490196, 1.        , 1.        ],
        [0.6509804 , 0.654902  , 0.2509804 , 1.        ]],

       [[0.58431375, 0.44705883, 0.24705882, 1.        ],
        [0.41960785, 0.3254902 , 1.        , 1.        ]],

       [[0.23137255, 0.3137255 , 0.5254902 , 1.        ],
        [0.70980394, 0.7411765 , 0.5568628 , 1.        ]]])
Related