Question

I have a numpy array with maximum value num. I would like to scale all the values in the array by newMaxValue/num so that the new maximum value of array is newMaxValue. I tried to convert the array to float and make the division afterwards but I cannot seem to divide and multiply it successfully. I always end up with a zero valued array. What is the correct way of doing this? Thanks

Was it helpful?

Solution

Make sure you convert the max to a float:

>>> from numpy import array
>>> a = array([1, 2, 3, 4, 5])
>>> new_max = 6 
>>> a / max(a)            # This is probably what happens to you
array([0, 0, 0, 0, 1])
>>> a / float(max(a))     # Convert that integer to a float and it'll work
array([ 0.2,  0.4,  0.6,  0.8,  1. ])
>>> a / float(max(a)) * new_max
array([ 1.2,  2.4,  3.6,  4.8,  6. ])

OTHER TIPS

import numpy as np
newMax = 20
myarr = np.random.randint(10, size=(10,2))
newarr = (myarr/float(np.amax(myarr))*newMax

PS: post your code, you probably made a simple coding mistake.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top