{:check ["true"]}

Index

Indexing and Slicing NDArrays

Slicing

In [1]:
import numpy as np

One dimensional indexing

In [2]:
x = np.arange(10)
x
Out[2]:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [3]:
x[5]
Out[3]:
5
In [4]:
x[5:8]
Out[4]:
array([5, 6, 7])
In [5]:
x[5:8] = 12
In [6]:
x
Out[6]:
array([ 0,  1,  2,  3,  4, 12, 12, 12,  8,  9])

Memory model

Slice of an array is a view. Modifications to the slice will modify the underlying array.

In [7]:
x_slice = x[5:8]
x_slice
Out[7]:
array([12, 12, 12])
In [8]:
x_slice[-1] = -100
x_slice
Out[8]:
array([  12,   12, -100])
In [9]:
x
Out[9]:
array([   0,    1,    2,    3,    4,   12,   12, -100,    8,    9])

Multi-dimensional indexing

In [10]:
y = np.array([[1,2,3],
              [4,5,6],
              [7,8,9]])
y
Out[10]:
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

There are two dimensions, so we need two indices to get a single entry in the matrix.

  • $y[i][j]$ is the $i$-th row, and $j$-th column.
  • $y[i,j]$ is equivalent. This is preferred.
In [11]:
y[0][2]
Out[11]:
3
In [12]:
y[0, 2]
Out[12]:
3

We can get an entire row:

  • $y[i]$ is the $i$-th row.
  • $y[i,:]$ is equivalent. This is preferred.
    • Fix the row to $i$,
    • Allow the column to be anything.
In [13]:
y[0]
Out[13]:
array([1, 2, 3])
In [14]:
y[0,:]
Out[14]:
array([1, 2, 3])

We can get an entire column.

  • $y[:, i]$ is the $i$-th column.
    • Allow the row to be anything.
    • Fix the column to $j$.
In [15]:
y[:, 2]
Out[15]:
array([3, 6, 9])

The general syntax of slicing along a dimension.

  • i:j: from $i$ to $j-1$ inclusive.
  • :j : from $0$ to $j-1$ inclusive.
  • i: : from $i$ to the last index in the dimension.
  • i:j:k: from $i$ to $j-1$ inclusive, and skip with step size $k$: $i$, $i+k$, $i+2k$, $\dots$
  • $[i,j,k,\dots]$: only indices that are included in the list
In [17]:
y[0:2, 2]
Out[17]:
array([3, 6])
In [18]:
y[0:, 2]
Out[18]:
array([3, 6, 9])
In [19]:
y[:2, 2]
Out[19]:
array([3, 6])
In [20]:
y[:2, :2]
Out[20]:
array([[1, 2],
       [4, 5]])
In [28]:
y[:,[2,1,0]]
Out[28]:
array([[3, 2, 1],
       [6, 5, 4],
       [9, 8, 7]])
In [30]:
y[:,2::-1]
Out[30]:
array([[3, 2, 1],
       [6, 5, 4],
       [9, 8, 7]])
In [31]:
y[1:2, :2]
Out[31]:
array([[4, 5]])

Note:

Observe y[1:2, :2] is not the same as y[1,:2].

  • Shape of y[1:2, :2] is (1,2). This is two dimensional.
  • Shape of y[1,:2] is (2,). This is one dimensional.