1

I have a 2d numpy array a:

a = np.array(range(0,25)).reshape(5,5)
---
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]
 [20 21 22 23 24]]

I want to find maxmium N values of each row and replace them with 100. I do this in a slow way:

N = 2
idx = a.argsort()
for i in range(a.shape[0]):
    a[i,idx[i][::-1][0:N]] = 100
print(a)
---
[[  0   1   2 100 100]
 [  5   6   7 100 100]
 [ 10  11  12 100 100]
 [ 15  16  17 100 100]
 [ 20  21  22 100 100]]

Actually the shape of my matrix is 6000*6000. How to do this in a better way? Like apply?

1 Answer 1

1

You can use argpartition here:

N=2
ix = a.argpartition(-N)[:,-N:]
a[np.arange(a.shape[0])[:,None], ix] = 100

print(a)
array([[  0,   1,   2, 100, 100],
       [  5,   6,   7, 100, 100],
       [ 10,  11,  12, 100, 100],
       [ 15,  16,  17, 100, 100],
       [ 20,  21,  22, 100, 100]])
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.