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

Time:10-29

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

[[[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.        ]]]

CodePudding user response:

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.        ]]])

CodePudding user response:

You can use this a[(a!=0).any(-1)], then use reshape and get what you want like below:

>>> 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.        ]]])

>>> np.reshape(a[(a!=0).any(-1)], (a.shape[0],-1,a.shape[-1]))
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.        ]]])
  • Related