[Tutor] normalize an array

Eike Welk eike.welk at gmx.net
Sat Nov 27 18:44:25 CET 2010


Hello John!

On Friday 26.11.2010 23:23:51 Peter Otten wrote:
> 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()

The underlying feature of Peter's solution is called broadcasting. For a 
detailed explanation look at:
http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html


Eike.


More information about the Tutor mailing list