3

I have an array data.

import numpy as np

data = np.array([[1,0,4,1,1,2,0],
                 [1,0,0,4,0,1,0],
                 [4,0,4,3,2,1,0],
                 [4,0,1,1,2,1,1]])

print(data)

If some non_zero elements (1,2,3,4) have more than 5 counts, I want to randomly extract and keep 5 positions and replace all other positions into 0s.

uniques, counts = np.unique(data, return_counts=True)
for unique, count in zip(uniques, counts):
    print (unique, count)

    if count > 5:       
       
       ids = np.random.choice(range(count), 5, replace=False)

How can I do it?

2
  • Keep just 5 positions or all positions of unique, non-zero elements when their counts are more than 5? Commented Jul 29, 2020 at 17:33
  • its to keep just 5 positions, if their counts are more than 5. Commented Jul 29, 2020 at 17:34

1 Answer 1

3
uniques, counts = np.unique(data, return_counts=True)
for unique, count in zip(uniques, counts):
    print (unique, count)
    if unique != 0 and count > 5:
       ids = np.random.choice(count, count-5, replace=False)
       data[tuple(i[ids] for i in np.where(data == unique))] = 0
Sign up to request clarification or add additional context in comments.

3 Comments

what would be an alternative to this line, data[tuple(i[ids] for i in np.where(data == unique))] = 0?
I could not understand that line
maybe this one more easily to understand, x,y = np.where(data == unique) for i in ids: data[x[i],y[i]] = 0

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.