Fastest way to zero out low values in array?

后端 未结 9 1498
忘掉有多难
忘掉有多难 2020-12-24 07:07

So, lets say I have 100,000 float arrays with 100 elements each. I need the highest X number of values, BUT only if they are greater than Y. Any element not matching this

9条回答
  •  生来不讨喜
    2020-12-24 07:35

    Using numpy:

    # assign zero to all elements less than or equal to `lowValY`
    a[a<=lowValY] = 0 
    # find n-th largest element in the array (where n=highCountX)
    x = partial_sort(a, highCountX, reverse=True)[:highCountX][-1]
    # 
    a[a

    Where partial_sort could be:

    def partial_sort(a, n, reverse=False):
        #NOTE: in general it should return full list but in your case this will do
        return sorted(a, reverse=reverse)[:n] 
    

    The expression a[a can be written without numpy as follows:

    for i, x in enumerate(a):
        if x < value:
           a[i] = 0
    

提交回复
热议问题