6

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?

10
  • I'm a bit confused because if you normalize an array of ints between 0 and 1 you'll just have an array of zeros and one. Which means you are going to lose a lot of distributional information. Commented Sep 11, 2014 at 23:09
  • 1
    @user3557216 this looks pretty efficient, but I would change array to another name to avoid shadowing the np.array() function... Commented Sep 12, 2014 at 6:45
  • 1
    @BKay, the array would turn the ints into floats. I normally send floats to begin with, but this is something the augmented function would handle additionally. Commented Sep 12, 2014 at 17:23
  • 1
    @Saullo Castro, I never do asterisk imports precisely to give me this freedom. Commented Sep 12, 2014 at 17:24
  • 2
    possible duplicate of how to normalize array numpy? Commented Sep 19, 2014 at 14:18

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah I have a function doing this. It's a bit niche, and maybe more the responsibility of the colormapper than of the data gatherer, so I guess this will do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.