min and max of NumPy arrays in Python within a certain range

Viewed 907

I am reading data from the sensor and its data always change over time, its data are between 0 and 255 as np.array.

I'd like to find min and max values between 3 and 250.

For example:

import numpy as np
a = np.array([0,1, 2, 10, 20, 100, 251, 255])
d = a.min()
c = a.max()
print (d,c)

The output is: (0, 255)

I'd like to be (10, 100)

Sometimes a = np.array([0,1, 3, 10, 20, 100, 249, 255])

I'd like to be (3, 249)

Please, your help.

3 Answers

One way is:

>>> a
array([0,1, 2, 10, 20, 100, 251, 255])
>>> arr_min = a[(a >= 3) & (a <= 250)].min()
>>> arr_max = a[(a >= 3) & (a <= 250)].max()
>>> (arr_min, arr_max)
(10, 100)

Other one is with scipy.stats.describe:

>>> from scipy.stats import describe
>>> describe(a[(3 <= a) & (a <= 250)]).minmax
(10, 100)

you can add conditions then check min and max

a = np.array([0,1, 2, 10, 20, 100, 251, 255])
print(a[(a>=3) & (a<=250)].min())
print(a[(a>=3) & (a<=250)].max())
10
100

Just create your own functions with using the existing in numpy:

import numpy as np

def my_min(input, min_, max_):
    m = input.min()

    if m > max_:
        return max_
    elif m < min_:
        return min_
    else:
        return m

def my_max(input, min_, max_):
    m = input.max()

    if m > max_:
        return max_
    elif m < min_:
        return min_
    else:
        return m

l1 = np.array([0, 1, 2, 10, 20, 100, 251, 255])
l2 = np.array([0,1, 3, 10, 20, 100, 249, 255])

print("({}, {})".format(my_min(l1, 10, 100), my_max(l1, 10, 100)))
print("({}, {})".format(my_min(l2, 3, 250), my_max(l2, 3, 250)))

Output:

(10, 100)
(3, 250)

Call the function like my_min(array, min, max)

Related