2

if I wanted to create a filter for a numpy array for several values how would I write that.

For instance say I want to do this...

clusters = np.array([4, 570, 56, 2, 5, 1, 1, 570, 32, 1])
fiveseventy_idx = np.where((clusters == 1) | (clusters == 570 ))
clusters = clusters[ fiveseventy_idx ]

In the above case i just want 2 items but say I had a much larger array and I want to filter for n number of items, I don't see how this could be done using this syntax if I had say 300 items I wanted out of the original array.

1
  • It can't really be done efficiently. You might be better with a for item in clusters: / if item in my_desired_set: construct. Commented Feb 28, 2022 at 4:11

1 Answer 1

3

If you had a sequence of values to search in your clusters, you could use np.isin:

>>> targets = [1, 570]  # Also could be: np.array([1, 570])
>>> np.isin(clusters, targets)
array([False,  True, False, False, False,  True,  True,  True, False,                       True]) 
>>> clusters[np.isin(clusters, targets)]
array([570,   1,   1, 570,   1])
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.