35 Using Numpy
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.
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.
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.