[Numpy-discussion] For-less code

Skipper Seabold jsseabold at gmail.com
Thu Feb 25 01:06:54 EST 2010


On Thu, Feb 25, 2010 at 12:52 AM, Gökhan Sever <gokhansever at gmail.com> wrote:
> Hello,
>
> I am working on a code shown at
> http://code.google.com/p/ccnworks/source/browse/trunk/thesis/part1/logn-fit.py
>
> I use the code to analyse a couple dataset also placed in the same
> directory. In the first part I use for-loops all over, but later decided to
> write them without using for loops. The script runs correctly for the two
> section, however I have a few question regarding to the for-less structures:
>
> This part is taken after line 371:
>
> gm10 = np.exp((1/Nt10)*(h10*np.log(Dp)).sum(axis=1))
> gsd10 =
> np.exp(((1/Nt10)*(h10*np.log(Dp/gm10[:,np.newaxis])**2).sum(axis=-1))**0.5)
>
> dN_dDp10 =
> (Nt10[:,np.newaxis]/((2*np.pi)**0.5*np.log(gsd10[:,np.newaxis])*d))*np.exp(-(np.log(d)-\
>
> np.log(gm10[:,np.newaxis]))**2/(2*np.log(gsd10[:,np.newaxis])**2))
>
> a10 = (dN_dDp10[0:300,d >= dc10u]*0.001).sum(axis=1)
>
> Shape informations for the arrays as follow:
>
> I[306]: gm10.shape; gsd10.shape, Dp.shape, d.shape, dN_dDp10.shape,
> a10.shape
> O[306]: (300,), (300,), (11,), (991,), (300, 991), (300,)
>
> 1-) In gsd10 line what does axis=-1 really means, and why negative axis
> value is allowed?
>

-1 in this case is the last axis I believe.  gsd10.shape[-1]

Or just like in python

[1,2,3,4][-1]
4

> 2-) [:,np.newaxis] decreases the readability of the code. Is there any
> alternative for it?
>

I find [:,None] to be the easiest unless I want to be really explicit
about a reshape.  It's probably just as bad though.

np.ones(8).shape
(8,)

np.expand_dims(np.ones(8),1).shape
(8, 1)

np.ones(8).reshape(8,-1).shape
(8, 1)

> 3-) In the last line (dN_dDp10[0:300,d >= dc10u]) could I achieve the same
> result with different syntax? I have found it somewhat not in accordance
> with the previous lines.
>

If it's an array you could just define it once as index_d or something
beforehand to increase readability?

Skipper

> Thanks for your time and comments.
>
> --
> Gökhan
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
>



More information about the NumPy-Discussion mailing list