Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Normalizing data to certain range of values

I am a new in Python, is there any function that can do normalizing a data?

For example, I have set of list in range 0 - 1 example : [0.92323, 0.7232322, 0,93832, 0.4344433]

I want to normalize those all values to range 0.25 - 0.50

Thank you,

like image 736
user46543 Avatar asked Dec 03 '22 20:12

user46543


1 Answers

The following function considers the generic case:

def normalize(values, bounds):
    return [bounds['desired']['lower'] + (x - bounds['actual']['lower']) * (bounds['desired']['upper'] - bounds['desired']['lower']) / (bounds['actual']['upper'] - bounds['actual']['lower']) for x in values]

Use:

normalize(
    [0.92323, 0.7232322, 0.93832, 0.4344433],
    {'actual': {'lower': 0, 'upper': 1}, 'desired': {'lower': 0.25, 'upper': 0.5}}
) # [0.4808075, 0.43080805, 0.48458, 0.35861082499999997]

normalize(
    [5, 7.5, 10, 12.5, 15],
    {'actual':{'lower':5,'upper':15},'desired':{'lower':1,'upper':2}}
) # [1.0, 1.25, 1.5, 1.75, 2.0]

I chose a two-level dict as the argument but you could give it in multiple ways, for example in two separate tuples, one for the actual bounds and the other for the desired, being the first element the lower bound and the second the upper:

def normalize(values, actual_bounds, desired_bounds):
    return [desired_bounds[0] + (x - actual_bounds[0]) * (desired_bounds[1] - desired_bounds[0]) / (actual_bounds[1] - actual_bounds[0]) for x in values]

Use:

   normalize(
    [0.92323, 0.7232322, 0.93832, 0.4344433],
    (0,1),
    (0.25,0.5)
) # [0.4808075, 0.43080805, 0.48458, 0.35861082499999997]

normalize(
    [5, 7.5, 10, 12.5, 15],
    (5,15),
    (1,2)
) # [1.0, 1.25, 1.5, 1.75, 2.0]
like image 162
Adirio Avatar answered Dec 06 '22 11:12

Adirio