[SciPy-user] How to use where
Thu Aug 21 23:18:12 CDT 2008
2008/8/21 Dave <firstname.lastname@example.org>:
> 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 : listofvectors = rand(100,2)
> In : bound = array([0.5,0.8])
> In : idx = all(listofvectors < bounds,axis=1)
> In : 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.
More information about the SciPy-user