Efficient thresholding filter of an array with numpy

后端 未结 1 1669
别跟我提以往
别跟我提以往 2020-11-30 19:09

I need to filter an array to remove the elements that are lower than a certain threshold. My current code is like this:

threshold = 5
a = numpy.array(range(1         


        
相关标签:
1条回答
  • 2020-11-30 20:05

    b = a[a>threshold] this should do

    I tested as follows:

    import numpy as np, datetime
    # array of zeros and ones interleaved
    lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()
    
    t0 = datetime.datetime.now()
    flt = lrg[lrg==0]
    print datetime.datetime.now() - t0
    
    t0 = datetime.datetime.now()
    flt = np.array(filter(lambda x:x==0, lrg))
    print datetime.datetime.now() - t0
    

    I got

    $ python test.py
    0:00:00.028000
    0:00:02.461000
    

    http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays

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