From their website (http://www.numpy.org/):
NumPy is the fundamental package for scientific computing with Python.
- a powerful N-dimensional array object
- sophisticated (broadcasting) functions
- tools for integrating C/C++ and Fortran code
- useful linear algebra, Fourier transform, and random number capabilities
You can import "numpy
" as
In [1]:
import numpy as np
In standard Python, data is stored as lists, and multidimensional data as lists of lists. In numpy
, however, we can now work with arrays. To get these arrays, we can use np.asarray
to convert a list into an array. Below we take a quick look at how a list behaves differently from an array.
In [2]:
# We first create an array `x`
start = 1
stop = 11
step = 1
x = np.arange(start, stop, step)
print(x)
We can also manipulate the array. For example, we can:
In [3]:
x * 2
Out[3]:
In [4]:
x ** 2
Out[4]:
In [5]:
(x**2) + (5*x) + (x / 3)
Out[5]:
If we want to set up an array in numpy, we can use range to make a list and then convert it to an array, but we can also just create an array directly in numpy. np.arange
will do this with integers, and np.linspace
will do this with floats, and allows for non-integer steps.
In [6]:
print(np.arange(10))
print(np.linspace(1,10,10))
Last week we had to use a function or a loop to carry out math on a list. However with numpy we can do this a lot simpler by making sure we're working with an array, and carrying out the mathematical operations on that array.
In [7]:
x=np.arange(10)
print(x)
print(x**2)
In numpy, we also have more options for quickly (and without much code) examining the contents of an array. One of the most helpful tools for this is np.where
. np.where
uses a conditional statement on the array and returns an array that contains indices of all the values that were true for the conditional statement. We can then call the original array and use the new array to get all the values that were true for the conditional statement.
There are also functions like max
and min
that will give the maximum and minimum, respectively.
In [8]:
# Defining starting and ending values of the array, as well as the number of elements in the array.
start = 0
stop = 100
n_elements = 201
x = np.linspace(start, stop, n_elements)
print(x)
And we can select only those values that are divisible by 5:
In [9]:
# This function returns the indices that match the criteria of `x % 5 == 0`:
x_5 = np.where(x%5 == 0)
print(x_5)
# And one can use those indices to *only* select those values:
print(x[x_5])
Or similarly:
In [10]:
x[x%5 == 0]
Out[10]:
And you can find the max
and min
values of the array:
In [11]:
print('The minimum of `x` is `{0}`'.format(x.min()))
print('The maximum of `x` is `{0}`'.format(x.max()))
Numpy also provides some tools for loading and saving data, loadtxt and savetxt. Here I'm using a function called transpose so that instead of each array being a row, they each get treated as a column.
When we load the information again, it's now a 2D array. We can select parts of those arrays just as we could for 1D arrays.
In [12]:
start = 0
stop = 100
n_elem = 501
x = np.linspace(start, stop, n_elem)
# We can now create another array from `x`:
y = (.1*x)**2 - (5*x) + 3
# And finally, we can dump `x` and `y` to a file:
np.savetxt('myfile.txt', np.transpose([x,y]))
# We can also load the data from `myfile.txt` and display it:
data = np.loadtxt('myfile.txt')
print('2D-array from file `myfile.txt`:\n\n', data, '\n')
# You can also select certain elements of the 2D-array
print('Selecting certain elements from `data`:\n\n', data[:3,:], '\n')
Matplotlib is a Python 2D plotting library which
From their website (http://matplotlib.org/):
Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. Matplotlib can be used in Python scripts, the Python and IPython shell, the jupyter notebook, web application servers, and four graphical user interface toolkits.
A great starting point to figuring out how to make a particular figure is to start from the Matplotlib gallery and look for what you want to make.
In [13]:
## Importing modules
%matplotlib inline
# Importing LaTeX
from matplotlib import rc
rc('text', usetex=True)
# Importing matplotlib and other modules
import matplotlib.pyplot as plt
import numpy as np
We can now load in the data from myfile.txt
In [14]:
data = np.loadtxt('myfile.txt')
The simplest figure is to simply make a plot. We can have multiple figures, but for now, just one. The plt.plot function will connect the points, but if we want a scatter plot, then plt.scatter will work.
In [15]:
plt.figure(1, figsize=(8,8))
plt.plot(data[:,0],data[:,1])
plt.show()
You can also pass the *data.T
value instead:
In [16]:
plt.figure(1, figsize=(8,8))
plt.plot(*data.T)
plt.show()
We can take that same figure and add on the needed labels and titles.
In [17]:
# Creating figure
plt.figure(figsize=(8,8))
plt.plot(*data.T)
plt.title(r'$y = 0.2x^{2} - 5x + 3$', fontsize=20)
plt.xlabel('x value', fontsize=20)
plt.ylabel('y value', fontsize=20)
plt.show()
There's a large number of options available for plotting, so try using the initial code below, combined with the information here to try out a few of the following things: changing the line width, changing the line color
In [18]:
plt.figure(figsize=(8,8))
plt.plot(data[:,0],data[:,1])
plt.title(r'$y = 0.2x^{2} - 5x + 3$', fontsize=20)
plt.xlabel('x value', fontsize=20)
plt.ylabel('y value', fontsize=20)
plt.show()