Hanfei Sun
Hanfei Sun

Reputation: 47051

Scale(or normalize) an array like this in numpy?

In numpy, the original array has the shape(2,2,2) like this

[[[0.2,0.3],[0.1,0.5]],[[0.1,0.3],[0.1,0.4]]]

I'd like to scale the array so that the max value of the a dimension is 1 like this:

As max([0.2,0.1,0.1,0.1]) is 0.2, and 1/0.2 is 5, so for the first element of the int tuple, multiple it by 5.

As max([0.3,0.5,0.3,0.4]) is 0.5, and 1/0.5 is 2, so for the second element of the int tuple, multiple it by 2

So the final array is like this:

[[[1,0.6],[0.5,1]],[[0.5,0.6],[0.5,0.8]]]

I know how to multiple an array with an integer in numpy, but I'm not sure how to multiple the array with different factor. Does anyone have ideas about this?

Upvotes: 1

Views: 4804

Answers (1)

Lee
Lee

Reputation: 31040

If your array = a:

>>> import numpy as np
>>> a = np.array([[[0.2,0.3],[0.1,0.5]],[[0.1,0.3],[0.1,0.4]]])

You can do this:

>>> a/np.amax(a.reshape(4,2),axis=0)
array([[[ 1. ,  0.6],
        [ 0.5,  1. ]],

       [[ 0.5,  0.6],
        [ 0.5,  0.8]]])

Upvotes: 4

Related Questions