1

I have a given numpy array as follows.

import numpy as np

data = np.array([[4,6,8,9,3,2,4,4,1], # no of 0s == 0
                  [4,6,8,9,3,0,0,4,0], # no of 0s == 3
                  [4,6,0,9,0,2,0,4,0], # no of 0s == 4
                  [4,6,8,0,3,0,0,0,0], # no of 0s == 5
                  [4,6,8,9,3,2,0,4,0]]) # no of 0s == 2

From the given array, data , I have to extract 3 rows which contain the least 0s. So, the expected are, 1st, last, and second rows.

res = np.array([[4,6,8,9,3,2,4,4,1], # no of 0s == 0
                      [4,6,8,9,3,0,0,4,0], # no of 0s == 3                      
                      [4,6,8,9,3,2,0,4,0]]) # no of 0s == 2

How can I do it guys?

1 Answer 1

1

Sum on your condition and partition.

n = 3
c = (data == 0).sum(1)
mn = np.argpartition(c, n)[:n]
data[mn]

array([[4, 6, 8, 9, 3, 2, 4, 4, 1],
       [4, 6, 8, 9, 3, 2, 0, 4, 0],
       [4, 6, 8, 9, 3, 0, 0, 4, 0]])

If you need the rows sorted by original index value and not number of zeros, replace the last line with:

data[np.sort(mn)]
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.