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

前端 未结 6 814
野性不改
野性不改 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

    Masked arrays in general are designed exactly for these kind of purposes. You can leverage masking zeros from an array (or ANY other kind of mask you desire, even masks that are more complicated than a simple equality) and do pretty much most of the stuff you do on regular arrays on your masked array. You can also specify an axis for which you wish to find the min along:

    import numpy.ma as ma
    mx = ma.masked_array(x, mask=x==0)
    mx.min()
    

    Example input:

    x = np.array([1.0, 0.0, 2.0])
    

    output:

    1.0
    

提交回复
热议问题