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]

		
Advertisements

Copying numpy arrays vs. copying lists

Today’s daily pitfall celebrates array copying. In a previous post, we talked about copying lists. If you’re using a numpy array (ndarray), however, the correct way to do it is using numpy’s convenient copy function.

import numpy as np
new_ndarray = np.copy(old_ndarray)

If you try using standard list copying methods – it won’t work, but Python won’t throw an exception, either. Took 30 minutes of algorithm debugging mixed in with a healthy dose of profanity before I tracked down the problem.

new_ndarray = old_ndarray[:]  # please don't do this