Min-max normalisation of a NumPy array

Referring to this Cross Validated Link, How to normalize data to 0-1 range?, it looks like you can perform min-max normalisation on the last column of foo.

v = foo[:, 1]   # foo[:, -1] for the last column
foo[:, 1] = (v - v.min()) / (v.max() - v.min())

foo

array([[ 0.        ,  0.        ],
       [ 0.13216   ,  0.06609523],
       [ 0.25379   ,  1.        ],
       [ 0.30874   ,  0.09727968]])

Another option for performing normalisation (as suggested by OP) is using sklearn.preprocessing.normalize, which yields slightly different results -

from sklearn.preprocessing import normalize
foo[:, [-1]] = normalize(foo[:, -1, None], norm='max', axis=0)

foo

array([[ 0.        ,  0.2378106 ],
       [ 0.13216   ,  0.28818769],
       [ 0.25379   ,  1.        ],
       [ 0.30874   ,  0.31195614]])

sklearn.preprocessing.MinMaxScaler can also be used (feature_range=(0, 1) is default):

from sklearn import preprocessing
min_max_scaler = preprocessing.MinMaxScaler()
v = foo[:,1]
v_scaled = min_max_scaler.fit_transform(v)
foo[:,1] = v_scaled
print(foo)

Output:

[[ 0.          0.        ]
 [ 0.13216     0.06609523]
 [ 0.25379     1.        ]
 [ 0.30874     0.09727968]]

Advantage is that scaling to any range can be done.


I think you want this:

foo[:,1] = (foo[:,1] - foo[:,1].min()) / (foo[:,1].max() - foo[:,1].min())