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

后端 未结 2 1553
刺人心
刺人心 2020-12-07 00:15

I have two NumPy arrays, e.g.:

a = [1,2,3,4,5]

and a filter array, e.g.:

f = [False, True, False, False, True]

len(a) == l         


        
相关标签:
2条回答
  • 2020-12-07 01:05

    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)
    
    0 讨论(0)
  • 2020-12-07 01:06

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

    0 讨论(0)
提交回复
热议问题