Set numpy array elements to zero if they are above a specific threshold

前端 未结 3 1371
南笙
南笙 2020-12-12 21:11

Say, I have a numpy array consists of 10 elements, for example:

a = np.array([2, 23, 15, 7, 9, 11, 17, 19, 5, 3])

Now I want to eff

3条回答
  •  一生所求
    2020-12-12 22:01

    Generally, list comprehensions are faster than for loops in python (because python knows that it doesn't need to care for a lot of things that might happen in a regular for loop):

    a = [0 if a_ > thresh else a_ for a_ in a]
    

    but, as @unutbu correctly pointed out, numpy allows list indexing, and element-wise comparison giving you index lists, so:

    super_threshold_indices = a > thresh
    a[super_threshold_indices] = 0
    

    would be even faster.

    Generally, when applying methods on vectors of data, have a look at numpy.ufuncs, which often perform much better than python functions that you map using any native mechanism.

提交回复
热议问题