Slicing and indexing with NumPy arrays

Indexing allows us to take a view of a ndarray by pointing out either what slice of columns and rows to visualize, or an index:

  1. Let's define a working array:
In: import numpy as np    M = np.arange(10*10, dtype=int).reshape(10,10)
  1. Our array is a 10 x 10 two-dimensional array. We can initially start by slicing it into a single dimension. The notation for a single dimension is the same as that in Python lists:
[start_index_included:end_index_exclude:steps]
  1. Let's say that we want to extract even rows from 2 to 8:
In: M[2:9:2,:]   Out: array([[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],            [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],            [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],  [80, 81, 82, 83, 84, 85, 86, 87, 88, ...

Get Python Data Science Essentials - Third Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.