我有一个十进制数字列表,如下所示:
[-23.5, -12.7, -20.6, -11.3, -9.2, -4.5, 2, 8, 11, 15, 17, 21]
我需要规范化这个列表以适应范围[-5,5]
。
我怎样才能在python中做到这一点?
要获得输入范围很容易:
old_min = min(input)
old_range = max(input) - old_min
这是棘手的部分。您可以乘以新范围并除以旧范围,但这几乎可以保证顶部存储桶只会得到一个值。您需要扩大输出范围,以使顶部存储桶与所有其他存储桶的大小相同。
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]
>>> 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]
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]
假设您的列表已排序:
# 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]
把事情简单化:
>>> 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]