Scale Numpy array to certain range

Viewed 17836

Similar to this question, I want to fit a Numpy array into a certain range, however unlike the linked question I don't want to normalise it. How can I do this efficiently? Is there a built-in method in Numpy?

To clarify with an example, where my_scale is the function I'm looking for and out_range defines the output range:

res = my_scale(np.array([-3, -2, -1], dtype=np.float), out_range)
assert res == [-1, 0, 1]
assert res != [-1, -2/3, -1/3]
2 Answers

This will do the trick:

def rescale_linear(array, new_min, new_max):
    """Rescale an arrary linearly."""
    minimum, maximum = np.min(array), np.max(array)
    m = (new_max - new_min) / (maximum - minimum)
    b = new_min - m * minimum
    return m * array + b

Note that there are (infinitely) many other, nonlinear ways of rescaling an array to fit within a new range, and this choice can be important depending on the circumstances.

Related