Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I extract rows of a 2D NumPy array by condition?

I have a 4*5 NumPy array and I want to retrieve rows in which all elements are less than 5.

arr = np.array([[0,2,3,4,5],[1,2,4,1,3], [2,2,5,4,6], [0,2,3,4,3]])
arr[np.where(arr[:,:] <= 4)] 

expected output:

[[1,2,4,1,3],[0,2,3,4,3]]

actual output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Any help is appreciated!

>Solution :

This actually quite simple. Just convert the entire array to booleans (each value is True if it’s less than 5, False otherwise), and use np.all with axis=1 to return True for each row where all items are True:

>>> arr[np.all(arr < 5, axis=1)]
array([[1, 2, 4, 1, 3],
       [0, 2, 3, 4, 3]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading