6.1 Introduction to numpy#
Numpy is a Python module for arrays of numbers, and for doing mathematical operations on them. Numpy is used for data analysis, plotting, linear algebra and is a very commonly used module in scientific Python.
Let’s import numpy:
import numpy as np
Now functions in numpy are accessible as np.array() for example.
The part as np is not necessary, but commonly done for slightly shorter code than typing numpy.array() every time (just like we imported matplotlib.pyplot as plt before).
A numpy vector is very much like a Python list, but you can do mathematics on the whole list at once.
We can create a numpy array from a Python list:
x = np.array([5, 2, 3.3])
print(x)
Note: the outer parentheses () belong to the function call. The inner [] define a Python list, which is used to provide the values for the vector being created.
There are other ways to create numpy arrays:
z = np.zeros(4)
e = np.ones(3)
a = np.zeros_like(x)
Use the cell below to print the newly created arrays. Are they what you expect?
### use this cell to print arrays z, e, a
6.1.1 Array math and plotting#
Now we can do math with the arrays:
y = x+e
print(y)
print(y*x)
Addition and multiplication are done element by element. There is also a dot product which you may know from vectors in mathematics:
a = np.array([ 1, 3, 0, 2])
b = np.array([-1, 2, 2, 0])
np.dot(a, b)
In Python, dot product can also be written as a@b, as shown below:
a@b
You cannot add arrays of different length, that results in an error:
print(x)
print(x + np.array([1, 2]))
But you can add an array and a single number:
print(x)
print(x + 1)
Numpy also has a similar function to range() which is np.arange():
np.arange(0.5, 4.5, 0.5)
Note that like range(), the end point is not included. Also note that rounding issues may change whether the final point is included or not.
If you want the end point to be included robustly, you can instead use np.linspace(start, end, N).
This creates an array of N equally spaced numbers where both start and end are included.
Use whichever is more convenient.
Attention
Note the differences!
With np.arange(0, 1, 0.1) you create an array starting at 0 with step size 0.1 (defined by the last number); the end point is not included: in this case the array has 10 elements [0, 0.1, 0.2, ..., 0.9].
With np.linspace(0, 1, 10) you create an array with 10 elements (defined by the last number), but since in this case the end point is included, it yields [0, 0.1111111, 0.22222222, ..., 0.88888889, 1].
Let’s now create an array x with equally spaced points, and evaluate a function on it.
x = np.linspace(0, 2*np.pi, 100)
y1 = np.cos(x)
Note we used np.cos(), which is similar to math.cos() but allows to use a numpy array as input, while the math equivalent can only work with single variables (scalars).
Attention
Functions from the math module do not work on numpy arrays as they expect single numbers. Always use their numpy equivalents.
Now each element of y1 equals the cosine of the corresponding element in x.
Use the cell below to print y1 to check.
### use this cell to print y1
Now we can use the arrays to plot the cosine function, using matplotlib.
import matplotlib.pyplot as plt
plt.plot(x, y1,'.')
plt.xlabel('x')
plt.ylabel('cos(x)')
6.1.2 Saving your plots#
One more important matplotlib function is saving plots in a file, so that you can use them in reports.
plt.plot(x, y1,'.-')
plt.xlabel('x')
plt.ylabel('cos(x)')
plt.savefig('cosplot.png')
Matplotlib will now save your plot in the file you specified. The file will be placed in the same folder / directory as your notebook. You can also specify the directory that you would want the image to be saved: check out the documentation of the savefig function here.
Note that in this interactive online environment, saving the file won’t work.
Matplotlib can handle several formats: .png (an image), .pdf (vector graphics, small files and often looks good), .svg (also vector graphics, can be edited in for example Inkscape)
Inkscape is a free and open-source vector graphics editor, worth learning.