NumPy arrays have other tricks when it comes to indexing mostly borrowed from Matlab and Octave. For example you can set up an indexing array of integers and these will be used to select elements along the corresponding dimension.

So for example:

myArray[[0,2],[1,2]]

picks out the myArray[0,1] and myArray[2,2] i.e.

array([2, 9])

You can use this technique to access arbitrary sub matrices of elements or regular sub matrices with indexes determined by other matrices.

There are lots of rules that govern how the lists of integers are applied i.e. what happens if you don't specify enough lists and so on but they are all obvious defaults.

Boolean Indexing

This is another indexing method borrowed from Matlab and Octave. You can use a Boolean array to pick out the elements you want to work with. If the Boolean array has a true element then the element in the array being indexed is selected.

Now at first thought this doesn't sound like a very useful option. Why would you go to the trouble of constructing a Boolean array to pick elements from an array? The answer is because it is very easy.

One of the things that NumPy introduces is elementwise functions and operations including elementwise comparisons.

This makes is easy to index an array on a condition. For example, suppose you wanted to set every element of an array smaller than 0.1 to zero:

myArray[myArray<0.1]=0

Now you can see why a Boolean index is useful!

Array Functions

There are many features of NumPy that are beyond the scope of this introduction but the availability of array functions is one that you need to know about. NumPy provides many apparent redundant copies of functions that are already provided in math or other modules. For example, np.sqrt seems to be identical to math.sqrt but it can be applied to arrays and it will be computed on each element:

If you want to compute an elementwise function on a NumPy array then check to see if it is provided within NumPy first - there are a lot of functions for general mathematics, bit manipulation and matrix arithmetic. For example to multiply two matrices together, A.B just use

A.dot(B)

There is so much more to say about NumPy so look out for another installment on working with arrays.