[Numpy-discussion] efficient use of numpy.where() and .any()

Pierre GM pgmdevlist@gmail....
Mon Apr 23 10:49:26 CDT 2007


On Monday 23 April 2007 10:37:57 Mark.Miller wrote:
> Greetings:
>
> In some of my code, I need to use large matrix of random numbers that
> meet specific criteria (i.e., some random numbers need to be removed and
> replaces with new ones).
>
> I have been working with .any() and .where() to facilitate this process.

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.

> Traceback (most recent call last):
>    File "<pyshell#71>", line 1, in <module>
>      while (0<a<1).any():

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.


More information about the Numpy-discussion mailing list