[SciPy-user] scipy sclicing
Anne Archibald
peridot.faceted@gmail....
Fri Oct 10 08:59:21 CDT 2008
2008/10/10 John [H2O] <washakie@gmail.com>:
>
> This seems to work:
>
> def slize(X,i,j):
> X = X[i,:]
> X = X[:,j]
> return X
>
> Problems with the approach?
No problem, per se, but it's a bit inefficient. I think the problem is
that multidimensional slicing with arrays doesn't work quite the way
you think it does. Let's say I have a 10 by 10 array X and I want rows
1, 3, and 5, and columns 2 and 4. I can't write
X[ np.array([1,3,5]), np.array([2,4]) ]
because that's not how numpy's fancy indexing works. When you supply
arrays of indices like this (as opposed to slices), the idea is that
you're picking out arbitrary collections of elements, not just
rectangular hunks. For example if I want elements (1,2), (3,4), and
(5,0) I can write:
X[ np.array([1,3,5]), np.array([2,4,0]) ]
But what if you want a rectangular slice? Naively, you would have to
construct two big arrays:
X[ np.array([[1,1],[3,3],[5,5]]), np.array([[2,4],[2,4],[2,4]]) ]
This will give you what you want, but building those index arrays is
annoying. Fortunately numpy's broadcasting can do it for you,
repeating each array along a new axis:
X[ np.array([1,3,5])[:,np.newaxis], np.array([2,4])[np.newaxis,:] ]
Anne
More information about the SciPy-user
mailing list