Index and slice

Integers, slices, 2-D [row, col], and integer lists.

NumPy uses one pair of brackets. For 2-D, write [row, col]. A slice of a row or column is still an array.

Goal

Select cells, rows, columns, and small blocks from a city × product grid.

One cell, one row, one column

# Rows: Nairobi, Mombasa, Kisumu  ·  cols: A, B, C
units = np.array(
    [
        [12, 7, 2],
        [9, 6, 0],
        [3, 11, 1],
    ],
    dtype=float,
)
print("Nairobi, product B:", units[0, 1])
print("Mombasa row:", units[1])
print("product C column:", units[:, 2])

units[1] is the whole Mombasa row. units[:, 2] is every city’s product C.

Blocks

units = np.array(
    [
        [12, 7, 2],
        [9, 6, 0],
        [3, 11, 1],
    ],
    dtype=float,
)
print(units[0:2, :2])

That is Nairobi and Mombasa, products A and B — shape (2, 2).

Integer lists (fancy index)

units = np.array(
    [
        [12, 7, 2],
        [9, 6, 0],
        [3, 11, 1],
    ],
    dtype=float,
)
print("Nairobi and Kisumu:")
print(units[[0, 2]])
print()
print("products A and C for those rows:")
print(units[np.ix_([0, 2], [0, 2])])

np.ix_ builds a grid from two integer lists. A plain units[[0, 2], [0, 2]] would pick two cells on the diagonal instead.

Negative indices

units = np.array(
    [
        [12, 7, 2],
        [9, 6, 0],
        [3, 11, 1],
    ],
    dtype=float,
)
print("last row:", units[-1])
print("last column:", units[:, -1])
Pitfall

Slices share memory with the parent. Integer lists copy. The next chapter is about that difference — do not assign into a slice until you have seen it.