Quick and Dirty – Indexing Numpy Arrays

Working with arrays can be a bit confusing to begin with. Here’s a quick and dirty array indexing guide to make sure you never get confused.

test = np.array([[ 0, 1, 2, 3, 4],
 [ 5, 6, 7, 8, 9],
 [10, 11, 12, 13, 14]])

Select the third row (row #2):

print test[2]

>> [10 11 12 13 14]

Select row 0 and 1:

print test[:2]

>> [[0 1 2 3 4]
 [5 6 7 8 9]]

Select the last row:

print test[-1]

>> [10 11 12 13 14]

Select column 2:

print test[:,2]

>> [ 2  7 12]
Select elements 0 and 1 in column 2:
print test [0:2, 2]

>> [2 7]