The Python Oracle

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

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

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5 Looping

--

Chapters
00:00 Question
00:48 Accepted answer (Score 38)
01:11 Answer 2 (Score 4)
01:36 Thank you

--

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

Accepted answer links:
[boolean indexing]: http://docs.scipy.org/doc/numpy/referenc...

--

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)