Indexing and Slicing Arrays

Array indexing selects values by position.

As with lists, indexing starts at 0.

Index a matrix with row and column

For a two-dimensional array:

A[row, column]

Example:

This reads row 0, column 1, which is 2.

Slice rows and columns

Use : to mean “all of this axis.”

A[0, :]

means row 0, all columns.

A[:, 1]

means all rows, column 1.

Rows and columns

Runs locally with Python in your browser.

Ready to run.

Slices preserve array structure

A[0, 1] selects one scalar value.

A[0, :] selects a one-dimensional array.

Those are different shapes. Inspect them when unsure:

print(A[0, :].shape)
Exercise: Select a column

Which expression selects column 1 from all rows of A?

Answer it first, then check.

Hint

The row position comes first. Keep every row with :, then select column index 1.

Solution

Use:

A[:, 1]

The : keeps all rows, and 1 selects the second column because indexing starts at zero.