How to filter a numpy array using another array's values? How to filter a numpy array using another array's values? numpy numpy

How to filter a numpy array using another array's values?


NumPy supports boolean indexing

a[f]

This assumes that a and f are NumPy arrays rather than Python lists (as in the question). You can convert with f = np.array(f).


If you don't already need numpy arrays, here's with a plain list:

import itertoolsprint itertools.compress(a, f)

For pre-2.7 versions of python, you must roll your own (see manual):

def compress(data, selectors):    return (d for d, s in itertools.izip(data, selectors) if s)