Home > Enterprise >  Numpy filter with `logical_or` from a list
Numpy filter with `logical_or` from a list

Time:02-01

I have the following code to filter from a numpy array

myarr = np.ones((4,2))
mask = np.logical_or(myarr == [0,1], myarr == [4,6]).all(axis=1)
...

This works fine if I know what I'm filtering ahead of time. However, I want to pass a list and call this eg.,

myarr = np.ones((4,2))
conds = [[5,9], [2,9], [4,6]]

mask = np.logical_or.reduce(np.array[conds)).all(axis=1) # this doesn't work
...

How do I go about doing this? Not sure I'm doing the right thing here. Any pointers are helpful.

CodePudding user response:

You can use broadcasting:

myarr = np.array([
                  [5, 9],
                  [2, 9],
                  [4, 6],
                  [9, 5],
                  [1, 1],
])

coords = np.array([[5,9], [2,9], [4,6]])
(myarr == coords[:,None]).all(-1).any(0)
# array([ True,  True,  True, False, False])
  •  Tags:  
  • Related