Surjya Narayana Padhi
Surjya Narayana Padhi

Reputation: 7841

How to normalize a list of positive and negative decimal number to a specific range

I have a list of decimal numbers as follows:

[-23.5, -12.7, -20.6, -11.3, -9.2, -4.5, 2, 8, 11, 15, 17, 21]

I need to normalize this list to fit into the range [-5,5].
How can I do it in python?

Upvotes: 8

Views: 19822

Answers (5)

Mark Ransom
Mark Ransom

Reputation: 308121

To get the range of input is very easy:

old_min = min(input)
old_range = max(input) - old_min

Here's the tricky part. You can multiply by the new range and divide by the old range, but that almost guarantees that the top bucket will only get one value in it. You need to expand your output range so that the top bucket is the same size as all the other buckets.

new_min = -5
new_range = 5 + 0.9999999999 - new_min
output = [floor((n - old_min) / old_range * new_range + new_min) for n in input]

Upvotes: 14

timss
timss

Reputation: 10260

Keep it simple:

>>> foo = [-23.5, -12.7, -20.6, -11.3, -9.2, -4.5, 2, 8, 11, 15, 17, 21]
>>> [i for i in foo if int(i) in range(-5, 5)]
[-4.5, 2]

Additionally, if you want the result to just be integers:

>>> [int(i) for i in foo if int(i) in range(-5, 5)]
[-4, 2]

Upvotes: -4

John La Rooy
John La Rooy

Reputation: 304137

>>> L = [-23.5, -12.7, -20.6, -11.3, -9.2, -4.5, 2, 8, 11, 15, 17, 21]
>>> normal = map(lambda x, r=float(L[-1] - L[0]): ((x - L[0]) / r)*10 - 5, L)
>>> normal
[-5.0, -2.5730337078651684, -4.348314606741574, -2.2584269662921352, -1.7865168539325844, -0.7303370786516856, 0.7303370786516847, 2.0786516853932575, 2.752808988764045, 3.6516853932584272, 4.101123595505618, 5.0]

Upvotes: 4

mdscruggs
mdscruggs

Reputation: 1212

original_vals = [-23.5, -12.7, -20.6, -11.3, -9.2, -4.5, 2, 8, 11, 15, 17, 21 ]

# get max absolute value
original_max = max([abs(val) for val in original_vals])

# normalize to desired range size
new_range_val = 5
normalized_vals = [float(val)/original_max * new_range_val for val in original_vals]

Upvotes: 1

Michael
Michael

Reputation: 2261

Assuming your list is sorted:

# Rough code
# Get the range of the list
r = float(l[-1] - l[0])
# Normalize
normal = map(lambda x: (x - l[0]) / r, l)

Basically, you want to adjust the base of the list into a different range. This will normalize your original list into [0, 1]

Upvotes: 0

Related Questions