Aventinus
Aventinus

Reputation: 1382

How To Normalize Array Between 1 and 10?

I have a numpy array with the following integer numbers:

[10 30 16 18 24 18 30 30 21 7 15 14 24 27 14 16 30 12 18]

I want to normalize them to a range between 1 and 10.

I know that the general formula to normalize arrays is:

enter image description here

But how am I supposed to scale them between 1 and 10?

Question: What is the simplest/fastest way to normalize this array to values between 1 and 10?

Upvotes: 4

Views: 10017

Answers (1)

Your range is actually 9 long: from 1 to 10. If you multiply the normalized array by 9 you get values from 0 to 9, which you need to shift back by 1:

start = 1
end = 10
width = end - start
res = (arr - arr.min())/(arr.max() - arr.min()) * width + start

Note that the denominator here has a numpy built-in named arr.ptp():

res = (arr - arr.min())/arr.ptp() * width + start

Upvotes: 8

Related Questions