NumPy offers several ways of selecting slices of arrays. Array views refer to the original data buffer of an array, but with different offsets, shapes, and strides. They only permit strided selections (that is, with linearly spaced indices). NumPy also offers specific functions to make arbitrary selections along one axis. Finally, fancy indexing is the most general selection method, but it is also the slowest as we will see in this recipe. Faster alternatives should be chosen when possible.
We suppose that NumPy has been imported and that the id
function has been defined (see the Understanding the internals of NumPy to avoid unnecessary array copying recipe).