As described in the previous lecture, numpy
arrays allow us to write highly readable and performant code when working with batches of numbers. In the next couple lectures, we'll go into a bit more detail about how to create, modify, and retrieve information from arrays.
As we already discussed, the simplest way to create small, custom arrays in numpy
is by transforming a list into an array.
import numpy as np
L = [1, 2, 3, 4]
a = np.array(L)
a
array([1, 2, 3, 4])
numpy
also offers functions for building a number of common arrays.
n = 3
np.zeros(n)
array([0., 0., 0.])
np.ones(n)
array([1., 1., 1.])
# random numbers between 0 and 1
np.random.rand(n)
array([0.82969143, 0.84623333, 0.95229689])
# an array version of range()
np.arange(n)
array([0, 1, 2])
# 3 evenly-spaced points between 0 and 1, inclusive
np.linspace(0, 1, 3)
array([0. , 0.5, 1. ])
numpy
arrays have dimensions (or axes). So far, we've only worked with one-dimensional arrays. A good way to check the dimensions of an array is with the shape
attribute:
a = np.ones(n)
a.shape
(3,)
This says that a
has a single dimension, and has three entries along that dimension. Here's a 2d array:
A = np.ones((n, n))
A.shape
(3, 3)
Now, A
has two dimensions, and has three entries along each dimension. For 2-dimensional arrays, numpy
will helpfully print out the array in format that makes the dimensions clear.
A
array([[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]])
You can create arrays of arbitrary numbers of dimensions, although it might be confusing to keep track of them after a while...
A = np.ones((n, n, n))
A
array([[[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]], [[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]], [[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]]])
A.shape
(3, 3, 3)
The reshape
method allows you to alter the dimensions of an array. For example, let's initialize a 1d array and transform it into a 2d array.
a = np.arange(15)
a
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
A = a.reshape(3, 5) # number of "rows" and "columns"
A
array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]])
We can also undo this operation:
a = A.reshape(15)
a
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])