35  Using Numpy

Tip

Make sure you run the code cell below before any of the others. This will import the numpy package, and it will be remembered until you move to a different page or refresh this page.

Let’s create some numpy arrays!

Pay close attention to the use of the square brackets in the following examples.

35.1 Homogeneity and Dimension Lengths

NumPy arrays are homogenous. This means that you can only store the same type of data (e.g. floats, integers etc) across the array.

The dimensions of a NumPy array must also be the same length consistently across the array (but can differ across dimensions).

For example, we can have an array which represents 3 departments, with 4 groups in each, and 10 people in each group. But we can’t have more or fewer than 10 people in each group, or more or fewer than 4 groups in each department. For real world data, this means we will sometimes have 0 or missing data for some values, and we deal with that differently depending on what we’re trying to represent.

To hammer this home, the below is NOT valid (but NumPy will let you do it, it’s just it won’t work as you think - you’ll end up with a 1D array with two values which are references to two lists) :

35.2 Referring to values (indexing) in Numpy arrays

To refer to a value in a NumPy array, we specify the index of the value we want in each dimension, starting with the “outermost” dimension.

Tip

Remember - in Python we start counting from 0!

So the ‘first’ element in a numpy array will be 0, the ‘second’ will be 1, and so on.

Run each of the cells below and try to understand how the indexing is working in each case.

35.3 Slicing numpy arrays

Just as with lists, we can use slicing to carve out a bit of a multidimensional NumPy array to return only the values we want.

The principle is the same for 3D+ arrays - remember, just count from the outside in.

35.4 Updating Values

Just like a list, we can update values in a NumPy array just by specifying the indices of the elements we want to update, and the new values.

Tip

NOTE : A lot of the examples you’re about to see use only one or two dimensional arrays for simplicity of understanding. But the same principles apply to arrays of any dimension.