IPython notebook is a web based interactive computational environment with code, text, mathematics, plot and exectution all in the same place. It's how we'll be doing the whole course, though we wouldn't use it for more script based programming, for that we suggest you use Spyder or your pet text editor.
A few shortcuts to make your life easier:
Words are useful, but what’s more useful are the sentences and stories we build with them. Similarly, while a lot of powerful tools are built into languages like Python, even more live in the libraries they are used to build.
Numpy is one of the essential libraries we use in python. We can import it like so:
We're going to demonstrate how to use the NumPy library with some statistics on arthuritis patient inflammmation. We can import csv files, where the data currently is, like so:
So lets examine this. By typing
numpy.loadtxt() we're saying, from the numpy library use the loadtxt function. It is the equivalent of selecting a file from a directory, or saying thing.component, for example, car.tyres might say, from the car I would like to inspect the tyres.
loadtxt() is a function call, which in this case has two arguments passed to it. The filename and the delimiter, both need to be input as character strings.
Character strings are sequences of characters enclosed in either
''. We typically use these in keyword argument calls to function, as above, and output to the console, more of which later.
Now if we type the variable the file is attached to into the interpreter, we see the data held within it as an array, with the delimiter
, seperating all the values.
The fact that this array is saved to a variable means that the array is stored in the computer's memory. Variables are an essential part of programming. Lets look at them in more detail. We can assign values to variables
Do some fancy printing with them, throwing in a bit of string usage too.
We can also use variables to define other variables
and then we can change the temperature in Kelvin
Note that changing the temperature in Kelvin does not change the previous temperature we used to calculate it in the first place
Now back to the patients. We have the patient infomation stored in memory as the variable
p_data, and we can check it's still there with
type, lets find out more about the array.
These two commands tell us that the variable is a NumPy array and then the extent of the array. In this case the rows are individual patients and the columns are their daily inflammation measurements. In this case we have 60 rows and 40 columns, known as the dimensions of the array. Using these attributes we can index the data to extract single data values:
We can also index a specific row or column. This can my done by using a colon in our indexing. For example,
p_data[:,15] will give us column 15:
p_data[15,:] gives us the 15 row. The
: says give me all the elements in this domain.
Thus we can make the domain smaller and essentially crop the array. By using the colon between the two limits:
Arrays also know how to perform common mathematical operations on their values. The simplest operations with data are arithmetic: add, subtract, multiply, and divide. When you do such operations on arrays, the operation is done on each individual element of the array. Thus:
This will create a new array whose elements have the value of two times the value of the corresponding elements in
crop_arr. However what if instead of taking an array and doing arithmetic with a single value (as above) you did the arithmetic operation with another array of the same shape, the operation will be done on corresponding elements of the two arrays. Thus:
Often, we want to do more than add, subtract, multiply, and divide values of data. Arrays also know how to do more complex operations on their values. If we want to find the average inflammation for all patients on all days, for example, we can just ask the array for its mean value
mean is a method of the array, i.e., a function that belongs to it in the same way that the member
shape does. If variables are nouns, methods are verbs: they are what the thing in question knows how to do. We need empty parentheses for
data.mean(), even when we’re not passing in any parameters, to tell Python to go and do something for us.
data.shape doesn’t need
() because it is just a description but
data.mean() requires the
() because it is an action.
When analyzing data, though, we often want to look at partial statistics, such as the maximum value per patient or the average value per day. One way to do this is to create a new temporary array of the data we want, then ask it to do the calculation:
We don’t actually need to store the row in a variable of its own. Instead, we can combine the selection and the method call:
What if we need the maximum inflammation for all patients, or the average for each day? In this case we need to average across an 'axis' of the array i.e. in x or y if we consider the data as a 2D array.
To support this, most array methods allow us to specify the axis we want to work on. If we ask for the average across axis 0 (rows in our 2D example), we get:
As a quick check, we can ask this array what its shape is:
(40,) tells us we have an N×1 vector, so this is the average inflammation per day for all patients. If we average across axis 1 (columns in our 2D example), we get:
which is the average inflammation per patient across all days.
The mathematician Richard Hamming once said, “The purpose of computing is insight, not numbers,” and the best way to develop insight is often to visualize data. Visualization deserves an entire lecture (or course) of its own, but we can explore a few features of Python’s
matplotlib library here. While there is no “official” plotting library, this package is the de facto standard. First, we will import the
pyplot module from
matplotlib and use two of its functions to create and display a heat map of our data:
Let’s take a look at the average inflammation over time:
Here, we have put the average per day across all patients in the variable
ave_inflammation, then asked
matplotlib.pyplot to create and display a line graph of those values. The result is roughly a linear rise and fall, which is suspicious: based on other studies, we expect a sharper rise and slower fall. Let’s have a look at two other statistics:
The maximum value rises and falls perfectly smoothly, while the minimum seems to be a step function. Neither result seems particularly likely, so either there’s a mistake in our calculations or something is wrong with our data.
You can group similar plots in a single figure using subplots. This script below uses a number of new commands.
matplotlib.pyplot.figure() creates a space into which we will place all of our plots.
figsize tells Python how big to make this space. Each subplot is placed into the figure using the
subplot command. The
subplot command takes 3 parameters. The first denotes how many total rows of subplots there are, the second parameter refers to the total number of subplot columns, and the final parameters denotes which subplot your variable is referencing.
subplot is stored in a different variable (axes1, axes2, axes3). Once a subplot is created, the axes are can be titled using the
set_xlabel() command (or
set_ylabel()). Here are our three plots side by side:
The call to
loadtxt reads our data, and the rest of the program tells the plotting library how large we want the figure to be, that we’re creating three sub-plots, what to draw for each one, and that we want a tight layout. (Perversely, if we leave out that call to
fig.tight_layout(), the graphs will actually be squeezed together more closely.)
first, second = 'Grace', 'Hopper' third, fourth = second, first print third, fourth
element = 'oxygen' print('first three characters:', element[0:3]) print('last three characters:', element[3:6])What is the value of element[:4]? What about element[4:]? Or element[:]? What is element[-1]? What is element[-2]? Given those answers, explain what element[1:-1] does.