简体   繁体   中英

remove rows and columns from numpy array

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM