Home > Software design >  Resizing array - possibly an environment issue, seems to not like 0
Resizing array - possibly an environment issue, seems to not like 0

Time:09-27

I have a class task to resize an array to [0,1] ie. so that the smallest number becomes 0 and largest 1.

It seems to not like the 0, as whenever there is a 0 in the code it spits out an empty array, but doing e.g [5,1] works. The output is this for [0,1]:

array([], shape=(0, 1), dtype=int64)

Is there any way to make it work? Profs have said it's right and are unsure why it's not working. Collab is the env.

test = [0,1,2,3,4,5]
arr1 = np.array(test)
def rescale(a):
    """Return the rescaled version of a on the [0,1] interval."""
    a = (np.resize(a,[0, 1]))   
    return a 
    print(a)
rescale(arr1)

CodePudding user response:

If I understand correctly what you really want is to normalize the values of the array, so the title is a bit misleading.

np.resize() changes the shape of the array but it does not change the values.

When any of the dimensions in the shape given to resize() is zero, then the array becomes empty because the number of elements in the array is the product of the dimensions and if one of them is zero, the product is zero. That explains your output.

So if you'd like to normalize the values, check this post: How to normalize a NumPy array to within a certain range?

CodePudding user response:

You need to compute the increment per unit and multiply this increment with each value and add the start of your interval:

test = [0,1,2,3,4,5]

def rescale(a, interval):
    """Return the rescaled version of a on the [0,1] interval."""
    incr = (interval[1] - interval[0]) / (max(a) - min(a))
    
    a = [i*incr   interval[0] for i in a]
    return a 

rescale(test, [0, 1])
  • Related