[Numpy-discussion] efficient use of numpy.where() and .any()
Anne Archibald
peridot.faceted@gmail....
Mon Apr 23 11:25:58 CDT 2007
On 23/04/07, Pierre GM <pgmdevlist@gmail.com> wrote:
> Have you tried nonzero() ?
>
> a[a<0] = numpy.random.normal(0,1)
>
> will put a random number from the normal distribution where your initial a is
> negative. No Python loops needed, no Python temps.
When you say "no python temps" I guess you mean, no temporary
*variables*? If I understand correctly, this allocates a temporary
boolean array to hold the result of "a<0".
> The double condition (0<a<1) is not legit. You should try
> logical.and(a>0,a<1)
> or
> (a>0) & (a<1)
>
> Note the () around each condition in case #2.
This is an unfortunate limitation that comes from the fact that we
can't override the behaviour of python's logical operations. a<b<c
does the right thing for python scalars, but it does it by being
expanded to (approximately) "a<b and b<c", and "and" doesn't do the
right thing for arrays. The best we can do is override the bitwise
operators for boolean arrays. This is a shame as I often want to
select array elements that fall into a given range, and creating three
temporary arrays instead of one is unpleasant.
Anne
More information about the Numpy-discussion
mailing list