[SciPy-user] How to use where
Yosef Meller
yosefmel at post.tau.ac.il
Thu Aug 21 07:35:26 EDT 2008
On Thursday 21 August 2008 12:41:20 Alexander Borghgraef wrote:
> 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, ... ] )
I believe it's actually (array[ 1, 2, 4, 10, ... ], ) - note the comma at the
end. You get a tuple with only one array for the single dimension.
> listofvectors = listofvectors[ inside, : ]
> # shape is ( 1, 100, 2 )
What you need is:
listofvectors = listofvectors[ inside[0], : ]
or drop the colon:
listofvectors = listofvectors[inside]
> don't really get why numpy is doing this, anyone care to explain?
When you're using the result of where(), you're passing a sequence inside a
tuple. When a tuple of sequences is passed as one of the indices, it creates a
new dimension, whose size is the number of equal-length sequences passed in
the tuple. Play with it a bit:
In [1]: a = arange(1, 10).reshape(3,3)
In [2]: a
Out[2]:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
In [3]: a[([1,2],[1,2]),:]
Out[3]:
array([[[4, 5, 6],
[7, 8, 9]],
[[4, 5, 6],
[7, 8, 9]]])
In [4]: a[:,([1,2],[1,2])]
Out[4]:
array([[[2, 3],
[2, 3]],
[[5, 6],
[5, 6]],
[[8, 9],
[8, 9]]])
In [5]: a[r_[1,2],:] # what you would expect:
Out[5]:
array([[4, 5, 6],
[7, 8, 9]])
In [6]: a[(r_[1,2],),:] # new dimension.
Out[6]:
array([[[4, 5, 6],
[7, 8, 9]]])
More information about the SciPy-User
mailing list