How to normalize a list of positive and negative d

2020-02-28 10:17发布

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?

5条回答
Evening l夕情丶
2楼-- · 2020-02-28 10:41
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]
查看更多
Lonely孤独者°
3楼-- · 2020-02-28 10:42

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 = [int((n - old_min) / old_range * new_range + new_min) for n in input]
查看更多
别忘想泡老子
4楼-- · 2020-02-28 10:42
>>> 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]
查看更多
家丑人穷心不美
5楼-- · 2020-02-28 10:47

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]
查看更多
三岁会撩人
6楼-- · 2020-02-28 10:51

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]

查看更多
登录 后发表回答