1

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]])]
2
  • 1
    Are you sure the example outputs are from the same A1 matrix? I don't see 2 and 4 in there. Commented Feb 9, 2023 at 6:57
  • A1[~np.all(A1 != 0, axis=0)] ? Commented Feb 9, 2023 at 6:57

1 Answer 1

3

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_

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.