Fastest way to zero out low values in array?

后端 未结 9 1542
忘掉有多难
忘掉有多难 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:34

    There's a special MaskedArray class in NumPy that does exactly that. You can "mask" elements based on any precondition. This better represent your need than assigning zeroes: numpy operations will ignore masked values when appropriate (for example, finding mean value).

    >>> from numpy import ma
    >>> x = ma.array([.06, .25, 0, .15, .5, 0, 0, 0.04, 0, 0])
    >>> x1 = ma.masked_inside(0, 0.1) # mask everything in 0..0.1 range
    >>> x1
    masked_array(data = [-- 0.25 -- 0.15 0.5 -- -- -- -- --],
             mask = [ True False True False False True True True True True],
       fill_value = 1e+20)
    >>> print x.filled(0) # Fill with zeroes
    [ 0 0.25 0 0.15 0.5 0 0 0 0 0 ]
    

    As an affffded benefit, masked arrays are well supported in matplotlib visualisation library if you need this.

    Docs on masked arrays in numpy

提交回复
热议问题