简体   繁体   中英

Converting an array of numbers from an old range to a new range, where the lowest valued number is a 100 and the highest valued number is a 0?

Say we have an array of values of [2, 5, 7, 9, 3] I would want the 2 be a 100 since it's the lowest value and the 9 to be a 0 since it's the highest, and everything in between is interpolated, how would I go about converting this array? When I say interpolated I want the numbers to be the same distance apart in the new scale, so the 3 wouldn't quite be 100, but close, maybe around 95 or so.

Just scale the array into the [0, 100] , then minus all of them by 100. So, the solution is:

import numpy as np

arr = [2, 5, 7, 9, 3]

min_val = np.min(arr)
max_val = np.max(arr)
total_range = max_val - min_val

new_arr = [(100 - int(((i - min_val)/total_range) * 100.0)) for i in arr]

Notice if you desire all values in the specified range from maximum to minimum will be uniformly distributed, your example for 3 cannot happen. So, in this solution, 3 will be around 84 (not 95).

I hope I'm understanding the question correctly. If so my solution would be to sort the list and then scale it proportional to the difference between the highest and lowest value of the list divided by 100. Here is a quick code example that works fine:

a = [2, 5, 7, 9, 3]
a.sort()
b = []
for element in a:
    b.append(int(100 - (element - a[0]) * (100 / (a[-1]-a[0]))))
print(a)
print(b)

along the same lines but broken into smaller steps Plus practice in naming variables

a = [2,5,7,9,3]

a_min = min(a)
a_max = max(a)
a_diff = a_max - a_min

b=[]
for x in a:
    b += [(x- a_min)]
b_max = max(b)

c=[]
for x in b:
    c += [(1-(x/b_max))*100]
print('c: ',c)   

//c:  [100.0, 57.14285714285714, 28.57142857142857, 0.0, 85.71428571428572]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM