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
]:
import
numpy
as
np
rng
=
np
.
random
.
default_rng
(
seed
=
1701
)
x
=
rng
.
integers
(
100
,
size
=
10
)
(
x
)
Out
[
1
]:
[
90
40
9
30
80
67
39
15
33
79
]
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
))
X
Out
[
5
]:
array
([[
0
,
1
,
2
,
3
],
[
4
,
5
,
6
,
7
],
[
8
,
9
,
10
,
11
]])
Like with standard indexing, ...
Get Python Data Science Handbook, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.