如何将正负十进制数列表标准化为特定范围

时间:2013-05-13 03:28:09

标签: python list range normalize

我有一个十进制数列表如下:

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

我需要将此列表标准化以适应范围[-5,5] 我怎么能在python中做到这一点?

5 个答案:

答案 0 :(得分:11)

要获得输入范围非常简单:

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

这是棘手的部分。您可以乘以新范围并除以旧范围,但这几乎可以保证顶部存储桶只能获得一个值。您需要扩展输出范围,以使顶部存储桶与所有其他存储桶的大小相同。

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]

答案 1 :(得分:2)

>>> 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]

答案 2 :(得分:1)

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]

答案 3 :(得分:0)

假设您的列表已排序:

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

基本上,您希望将列表的基础调整到不同的范围。这会将原始列表标准化为[0,1]

答案 4 :(得分:-2)

保持简单:

>>> 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]

此外,如果您希望结果只是整数:

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