[Numpy-discussion] Numpy Advanced Indexing Question
Stéfan van der Walt
stefan@sun.ac...
Thu Jul 17 04:00:05 CDT 2008
2008/7/17 Robert Kern <robert.kern@gmail.com>:
> So the way fancy indexing interacts with slices is a bit tricky, and
> this is why we couldn't use the nicer syntax of cube[:,:,idx_k]. All
> axes with fancy indices are collected together. Their index arrays are
> broadcasted and iterated over. *For each iterate*, all of the slices
> are collected, and those sliced axes are *added* to the output array.
> If you had used fancy indexing on all of the axes, then the iterate
> would be a scalar value pulled from the original array. If you mix
> fancy indexing and slices, the iterate is the *array* formed by the
> remaining slices.
>
> So if idx_k is shaped (ni,nj,3), for example, cube[:,:,idx_k] will
> have the shape (ni,nj,ni,nj,3). So
> smallcube[:,:,i,j,k]==cube[:,:,idx_k[i,j,k]].
>
> Is that clear, or am I obfuscating the subject more?
Crystal, thank you for taking the time to explain! This is such
valuable information; we should consider adding a section to
numpy.doc.indexing or wherever is more appropriate.
>> For the constant slice case, I guess idx_k also have been (1, 1, 7)?
>>
>> The construction of the cube could probably be done using only
>>
>> cube.flat = np.arange(nk)
[...]
> If the RHS cannot be
> broadcasted to the right shape (in this case because it is not the
> same length as the final axis of the LHS), an error is raised. I find
> the reuse of the broadcasting concept to be more memorable, and robust
> over the (mostly) ad hoc use of plain repetition with .flat.
I've become used to exploiting the repeating property of .flat, and
forgot its dangers. Thanks for the reminder!
Cheers
Stéfan
More information about the Numpy-discussion
mailing list