Find the min/max excluding zeros in a numpy array (or a tuple) in python

前端 未结 6 815
野性不改
野性不改 2020-12-08 09:36

I have an array. The valid values are not zero (either positive or negetive). I want to find the minimum and maximum within the array which should not take zeros into accoun

6条回答
  •  伪装坚强ぢ
    2020-12-08 09:54

    If you can choose the "invalid" value in your array, it is better to use nan instead of 0:

    >>> a = numpy.array([1.0, numpy.nan, 2.0])
    >>> numpy.nanmax(a)
    2.0
    >>> numpy.nanmin(a)
    1.0
    

    If this is not possible, you can use an array mask:

    >>> a = numpy.array([1.0, 0.0, 2.0])
    >>> masked_a = numpy.ma.masked_equal(a, 0.0, copy=False)
    >>> masked_a.max()
    2.0
    >>> masked_a.min()
    1.0
    

    Compared to Josh's answer using advanced indexing, this has the advantage of avoiding to create a copy of the array.

提交回复
热议问题