[SciPy-user] Slicing 3D array using two 1D arrays not working
Travis E. Oliphant
Thu May 22 12:07:30 CDT 2008
Dharhas Pothina wrote:
> 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
> but if I try
> 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.
More information about the SciPy-user