[Tutor] normalize an array

Peter Otten __peter__ at web.de
Fri Nov 26 23:23:51 CET 2010


John wrote:

> I know this is a simple problem, but I want to do it the most
> efficient way (that is vectorized...)
> 
> import numpy as np
> 
> a = np.array(([1,2,3,4],[1,.2,3,4],[1,22,3,4]))
> b = np.sum(a,axis=1)
> 
> for i,elem in enumerate(a):
>     a[i,:] = elem/b[i]
 
> suggestions?

I'm not a numpy expert, but:

(a.transpose()/np.sum(a, axis=1)).transpose()

Peter



More information about the Tutor mailing list