Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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 account. For example if the numbers are only negative. Zeros will be problematic.

like image 279
Shan Avatar asked Aug 23 '11 16:08

Shan


People also ask

How do you find the max and min value of a numpy array?

numpy. amax() will find the max value in an array, and numpy. amin() does the same for the min value.

What is the way to find the maximum number in the numpy array in Python?

Here, we create a single-dimensional NumPy array of integers. Now try to find the maximum element. To do this we have to use numpy. max(“array name”) function.

How do you count the number of zeros in a numpy array?

To count all the zeros in an array, simply use the np. count_nonzero() function checking for zeros. It returns the count of elements inside the array satisfying the condition (in this case, if it's zero or not).


3 Answers

How about:

import numpy as np
minval = np.min(a[np.nonzero(a)])
maxval = np.max(a[np.nonzero(a)])

where a is your array.

like image 190
JoshAdel Avatar answered Oct 07 '22 06:10

JoshAdel


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.

like image 35
Sven Marnach Avatar answered Oct 07 '22 04:10

Sven Marnach


Here's another way of masking which I think is easier to remember (although it does copy the array). For the case in point, it goes like this:

>>> import numpy
>>> a = numpy.array([1.0, 0.0, 2.0])
>>> ma = a[a != 0]
>>> ma.max()
2.0
>>> ma.min()
1.0
>>> 

It generalizes to other expressions such as a > 0, numpy.isnan(a), ... And you can combine masks with standard operators (+ means OR, * means AND, - means NOT) e.g:

# Identify elements that are outside interpolation domain or NaN
outside = (xi < x[0]) + (eta < y[0]) + (xi > x[-1]) + (eta > y[-1])
outside += numpy.isnan(xi) + numpy.isnan(eta)
inside = -outside
xi = xi[inside]
eta = eta[inside]
like image 7
uniomni Avatar answered Oct 07 '22 04:10

uniomni