Normalize / Translate ndarray - Numpy / Python
You could use np.ptp
1 (peak to peak) in conjunction with np.min
to do this in the general case:
new_arr = (a - a.min())/np.ptp(a)
example:
>>> a = np.array([[-1., 0, 1], [0, 2, 1]])>>> np.ptp(a)3.0>>> aarray([[-1., 0., 1.], [ 0., 2., 1.]])>>> (a - a.min())/np.ptp(a)array([[ 0. , 0.33333333, 0.66666667], [ 0.33333333, 1. , 0.66666667]])
Of course, this still would give an error if a
consists of entirely zeros -- But the problem isn't well posed in that case.
1IIRC, np.ptp
calls np.max
and np.min
. If performance is really critical, you might what to create your own ptp
and save np.min
to a temporary variable so you don't calculate it twice.