NumPy ('Numerical Python') is the standard module for doing numerical work in Python. Its main feature is its array data type which allows very compact and efficient storage of homogenous (of the same type) data
There is a standard convention for importing numpy
, and that is as np
:
import numpy as np
Now that we have access to the numpy
package we can start using its features.
In many ways a NumPy array can be treated like a standard Python list
and much of the way you interact with it is identical. Given a list, you can create an array as follows:
python_list = [1, 2, 3, 4, 5, 6, 7, 8]
numpy_array = np.array(python_list)
print(numpy_array)
# ndim give the number of dimensions
print(numpy_array.ndim)
# the shape of an array is a tuple of its length in each dimension. In this case it is only 1-dimensional
print(numpy_array.shape)
# as in standard Python, len() gives a sensible answer
print(len(numpy_array))
nested_list = [[1, 2, 3], [4, 5, 6]]
two_dim_array = np.array(nested_list)
print(two_dim_array)
print(two_dim_array.ndim)
print(two_dim_array.shape)
It's very common when working with data to not have it already in a Python list but rather to want to create some data from scratch. numpy
comes with a whole suite of functions for creating arrays. We will now run through some of the most commonly used.
The first is np.arange
(meaning "array range") which works in a vary similar fashion the the standard Python range()
function, including how it defaults to starting from zero, doesn't include the number at the top of the range and how it allows you to specify a 'step:
np.arange(10) #0 .. n-1 (!)
np.arange(1, 9, 2) # start, end (exclusive), step
Next up is the np.linspace
(meaning "linear space") which generates a given floating point numbers starting from the first argument up to the second argument. The third argument defines how many numbers to create:
np.linspace(0, 1, 6) # start, end, num-points
Note how it included the end point unlike arange()
. You can change this feature by using the endpoint
argument:
np.linspace(0, 1, 5, endpoint=False)
np.ones
creates an n-dimensional array filled with the value 1.0
. The argument you give to the function defines the shape of the array:
np.ones((3, 3)) # reminder: (3, 3) is a tuple
Likewise, you can create an array of any size filled with zeros:
np.zeros((2, 2))
The np.eye
(referring to the matematical identity matrix, commonly labelled as I
) creates a square matrix of a given size with 1.0
on the diagonal and 0.0
elsewhere:
np.eye(3)
The np.diag
creates a square matrix with the given values on the diagonal and 0.0
elsewhere:
np.diag([1, 2, 3, 4])
Finally, you can fill an array with random numbers:
np.random.rand(4) # uniform in [0, 1]
np.random.randn(4) # Gaussian or normally distributed
Try executing these cells multiple times and notice how you get a different result each time.
Behind the scenes, a multi-dimensional NumPy array
is just stored as a linear segment of memory. The fact that it is presented as having more than one dimension is simply a layer on top of that (sometimes called a view). This means that we can simply change that interpretive layer and change the shape of an array very quickly (i.e without NumPy having to copy any data around).
This is mostly done with the reshape()
method on the array object:
my_array = np.arange(16)
my_array
my_array.shape
my_array.reshape((2, 8))
my_array.reshape((4, 4))
Note that if you check, my_array.shape
will still return (16,)
as reshaped
is simply a view on the original data, it hasn't actually changed it. If you want to edit the original object in-place then you can use the resize()
method.
You can also transpose an array using the transpose()
method which mirrors the array along its diagonal:
my_array.reshape((2, 8)).transpose()
my_array.reshape((4,4)).transpose()