[SciPy-user] How to use where
Chris Lee
c.j.lee@tnw.utwente...
Fri Aug 22 02:05:44 CDT 2008
Now that is nice. I had been using where with nonzero because I
misunderstood what all did and never even tried it :(
Nevertheless a code rewrite is not on the horizon :)
Cheers
Chris
On Aug 22, 2008, at 6:18 AM, Anne Archibald wrote:
> 2008/8/21 Dave <dave.hirschfeld@gmail.com>:
>> Alexander Borghgraef <alexander.borghgraef.rma <at> gmail.com>
>> writes:
>>
>>>
>>> Hi all,
>>>
>>> I'm trying to figure out here how 'where' works exactly. I'm working
>>> on a list of vectors which I represent as a 2D array, and I'd like
>>> to
>>> remove the vectors which are out of bounds. So after some
>>> experimenting I got to basically this:
>>>
>>> listofvectors = ...
>>> # shape is ( 100, 2 )
>>> bound = array( [ xmax, ymax ] )
>>> inside = where( all( listofvectors < bound, axis = 1 ) ) # inside
>>> is ( array[ 1, 2, 4, 10, ... ] )
>>> listofvectors = listofvectors[ inside, : ]
>>> # shape is ( 1, 100, 2 )
>>>
>>
>> In [1]: listofvectors = rand(100,2)
>>
>> In [2]: bound = array([0.5,0.8])
>>
>> In [3]: idx = all(listofvectors < bounds,axis=1)
>>
>> In [4]: inbounds = listofvectors[idx,:]
>>
>> I'm not sure of the utility of where - I tend to use boolean masks.
>> Is there any
>> reason one wouldn't use the code I posted above?
>
> No, in fact boolean masks are usually more efficient. The exception I
> would make is when you want to keep the index around for a while and
> when it's only a small fraction of the array elements: then it's more
> efficient to keep track of where the elements you want are. It's also
> sometimes useful to do manipulations on the positions of array
> elements, and you might care about the order of the result.
>
> It's also worth noting that none of these uses require "where"; fancy
> indexing can do the same thing.
>
> Finally, there is another, totally unrelated, operation of the
> function called "where": it can be used to build arrays:
>
> where(a<3, -1, a-4)
>
> produces an array that is -1 anywhere a<3, and is a-4 everywhere else.
> Having these two unrelated operations built into the same function is
> poor UI design, but we're stuck with it. For that reason, I only ever
> use where in this second mode.
>
> Anne
> _______________________________________________
> SciPy-user mailing list
> SciPy-user@scipy.org
> http://projects.scipy.org/mailman/listinfo/scipy-user
***************************************************
Chris Lee
Laser Physics and Nonlinear Optics Group
MESA+ Research Institute for Nanotechnology
University of Twente
Phone: ++31 (0)53 489 3968
fax: ++31 (0)53 489 1102
***************************************************
More information about the SciPy-user
mailing list