Chapter 10. Fancy Indexing
The previous chapters discussed how to access and modify portions of
arrays using simple indices (e.g., arr[0]), slices (e.g., arr[:5]),
and Boolean masks (e.g., arr[arr > 0]). In this chapter,
we’ll look at another style of array indexing, known as
fancy or vectorized indexing, in which we pass arrays of indices in
place of single scalars. This allows us to very quickly access and
modify complicated subsets of an array’s values.
Exploring Fancy Indexing
Fancy indexing is conceptually simple: it means passing an array of indices to access multiple array elements at once. For example, consider the following array:
In[1]:importnumpyasnprng=np.random.default_rng(seed=1701)x=rng.integers(100,size=10)(x)Out[1]:[9040930806739153379]
Suppose we want to access three different elements. We could do it like this:
In[2]:[x[3],x[7],x[2]]Out[2]:[30,15,9]
Alternatively, we can pass a single list or array of indices to obtain the same result:
In[3]:ind=[3,7,4]x[ind]Out[3]:array([30,15,80])
When using arrays of indices, the shape of the result reflects the shape of the index arrays rather than the shape of the array being indexed:
In[4]:ind=np.array([[3,7],[4,5]])x[ind]Out[4]:array([[30,15],[80,67]])
Fancy indexing also works in multiple dimensions. Consider the following array:
In[5]:X=np.arange(12).reshape((3,4))XOut[5]:array([[0,1,2,3],[4,5,6,7],[8,9,10,11]])
Like with standard indexing, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access