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.

Angus Campbell
  • 563
  • 4
  • 19
  • It can't really be done efficiently. You might be better with a `for item in clusters:` / `if item in my_desired_set:` construct. – Tim Roberts Feb 28 '22 at 04:11

1 Answers1

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])
aaossa
  • 3,763
  • 2
  • 21
  • 34