0

I have an array like this:

a = np.array([[1,2,3,4,5],
[6,0,8,9,10],
[11,12,13,14,15],
[16,0,0,19,20]])

And I would like to remove columns and rows where there is a 0 value, so the new a should be like:

array([[1,4,5],
[11,14,15]])

How to work this out using indexing?

1 Answer 1

2
>>> a[(a != 0).all(axis=1)][:,(a != 0).all(axis=0)]
array([[ 1,  4,  5],
       [11, 14, 15]])

Finding the elements of a that are non-zero is really easy:

>>> (a != 0)
array([[ True,  True,  True,  True,  True],
       [ True, False,  True,  True,  True],
       [ True,  True,  True,  True,  True],
       [ True, False, False,  True,  True]], dtype=bool)

And then you can just use all, specifying the axis, to find the rows you want to keep:

>>> (a != 0).all(axis=1)
array([ True, False,  True, False], dtype=bool)

and the same thing for the columns:

>>> (a != 0).all(axis=0)
array([ True, False, False,  True,  True], dtype=bool)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the explanation!

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.