Remove all zero rows and columns in one go in Python

Question:

I want to remove all zero rows and columns in one line from the array A1. I present the current and expected outputs.

import numpy as np

A1=np.array([[0, 0, 0],
            [0, 1, 2],
            [0, 3, 4]])

A1 = A1[~np.all(A1 == 0, axis=0)]
print([A1])

The current output is

[array([[0, 1, 2],
       [0, 3, 4]])]

The expected output is

[array([[1, 2],
        [3, 4]])]
Asked By: rajunarlikar123

||

Answers:

Not really sure your example works, but given the description in the title – for a matrix matrix, you can use

mask = matrix != 0
new_matrix = matrix[np.ix_(mask.any(1), mask.any(0))]

you can check out this post about np.ix_

Answered By: Hadar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.