user3557216
user3557216

Reputation: 269

NumPy array to bounded by 0 and 1?

Basically I have an array that may vary between any two numbers, and I want to preserve the distribution while constraining it to the [0,1] space. The function to do this is very very simple. I usually write it as:

def to01(array):
    array -= array.min()
    array /= array.max()
    return array

Of course it can and should be more complex to account for tons of situations, such as all the values being the same (divide by zero) and float vs. integer division (use np.subtract and np.divide instead of operators). But this is the most basic.

The problem is that I do this very frequently across stuff in my project, and it seems like a fairly standard mathematical operation. Is there a built in function that does this in NumPy?

Upvotes: 6

Views: 1228

Answers (1)

greschd
greschd

Reputation: 636

Don't know if there's a builtin for that (probably not, it's not really a difficult thing to do as is). You can use vectorize to apply a function to all the elements of the array:

def to01(array):
    a = array.min()
    # ignore the Runtime Warning
    with numpy.errstate(divide='ignore'):
        b = 1. /(array.max() - array.min())
    if not(numpy.isfinite(b)):
        b = 0
    return numpy.vectorize(lambda x: b * (x - a))(array)

Upvotes: 2

Related Questions