[SciPy-user] Slicing 3D array using two 1D arrays not working
Travis E. Oliphant
oliphant at enthought.com
Thu May 22 13:07:30 EDT 2008
Dharhas Pothina wrote:
> Hi,
>
> I have an array a 3D array 'a' (a.shape = a(6, 21216, 2) ) and I want to slice it using a[levels,nodes,:] where
> levels=array([2,4]),nodes=array([12,1234,4566,1233]) etc.
>
> I can do
>
> b=a[:,nodes,:]
> c=b[levels,:,:]
>
> but if I try
> c=a[levels,nodes,:]
>
> ValueError: shape mismatch: objects cannot be broadcast to a single shape
>
> is there something I am doing wrong or is this just not possible?
>
What is a[levels, nodes, :] supposed to return? If you are expecting
the cross-product, then I suspect what you want is
il, in = numpy.ix_(levels, nodes)
c = a[il, in,:]
Indexing with a list in NumPy returns an "element-byelement" result so
the two indexing lists have to have commensurate shapes. You get the
cross-product by fiddling with the dimensions and turn levels into a
(2,1)-array and nodes into a (1,4)-array. Then broadcasting handles
createing the (2,4)-shape set of indices that you may have been expecting.
That's all numpy.ix_ does is fiddle with the shapes to give you index
arrays for getting the cross-product.
-Travis
More information about the SciPy-User
mailing list