Making efficient array selections in NumPy
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.
Getting ready
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).
How to do it...
Let's create an array with a large number of rows. We will select slices of this array along the first dimension:
In [3]: n, d = 100000, 100 In [4]: a = np.random.random_sample((n, d)); aid = id(a)
Let's select one row from every 10 rows, using two different methods...