The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Fantascape Looping

--

Chapters
00:00 How To Filter A Numpy Array Using Another Array'S Values?
00:31 Accepted Answer Score 42
00:50 Answer 2 Score 3
01:07 Thank you

--

Full question
https://stackoverflow.com/questions/9296...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #arrays #filter #numpy

#avk47



ACCEPTED ANSWER

Score 42


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).




ANSWER 2

Score 3


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

import itertools
print 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)