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

Mark.Miller mpmusu@cc.usu....
Mon Apr 23 11:16:16 CDT 2007

Excellent suggestions...just a few comments:

Pierre GM wrote:
> 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() ?

Nonzero isn't quite what I'm after, as the tests are more complicated 
than what I illustrated in my example.

> a[a<0] = numpy.random.normal(0,1)

This is a neat construct that I didn't realize was possible.  However, 
it has the undesirable (in my case) effect of placing a single new 
random number in each locations where a<0.  While this could work, I 
ideally need a different random number chosen for each replaced value. 
Does that make sense?

> 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.

This makes perfect sense.  Thanks for pointing it out to me.  It should 
easily do the trick.

Any and all additional suggestions are greatly appreciated,


> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion@scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion

More information about the Numpy-discussion mailing list