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:
In [3]:
from __future__ import division, print_function
import numpy
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:
In [4]:
p_data = numpy.loadtxt(fname='data/inflammation-01.csv', delimiter=',')
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 ""
or ''
. 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.
In [ ]:
p_data
In [12]:
temp = 34
Reassign them
In [ ]:
temp = 37
Do some fancy printing with them, throwing in a bit of string usage too.
In [ ]:
print("The temperature of this spam is {0} please take it back".format(temp))
We can also use variables to define other variables
In [ ]:
temp_K = temp + 273
temp_K
and then we can change the temperature in Kelvin
In [ ]:
temp_K = temp_K + 10
temp_K
Note that changing the temperature in Kelvin does not change the previous temperature we used to calculate it in the first place
In [ ]:
temp
In [ ]:
%whos
In [10]:
print("The data from the file is now {0} and has attibutes {1}".format(type(p_data), p_data.shape))
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:
In [ ]:
print(file[12,15])
print(p_data[0,0])
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:
In [ ]:
p_data[:,15]
and p_data[15,:]
gives us the 15 row. The :
says give me all the elements in this domain.
In [ ]:
p_data[15,:]
Thus we can make the domain smaller and essentially crop the array. By using the colon between the two limits:
In [ ]:
crop_arr = p_data[10:20,10:20]
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:
In [ ]:
double_data = crop_arr * 2.0
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:
In [ ]:
trip_data = double_data + crop_arr
trip_data
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
In [ ]:
print(p_data.mean())
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.
In [ ]:
print( 'maximum inflammation:', p_data.max())
print('minimum inflammation:', p_data.min())
print('standard deviation:', p_data.std())
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:
In [ ]:
patient_0 = p_data[0, :] # 0 on the first axis, everything on the second
print( 'maximum inflammation for patient 0:', patient_0.max())
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:
In [ ]:
print('maximum inflammation for patient 2:', p_data[2, :].max())
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:
In [ ]:
print(p_data.mean(axis=0))
As a quick check, we can ask this array what its shape is:
In [ ]:
print(p_data.mean(axis=0).shape)
The expression (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:
In [ ]:
print(p_data.mean(axis=1))
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:
In [ ]:
import matplotlib.pyplot
image = matplotlib.pyplot.imshow(p_data)
matplotlib.pyplot.show(image)
Let’s take a look at the average inflammation over time:
In [ ]:
ave_infl = p_data.mean(axis=0)
ave_plot = matplotlib.pyplot.plot(ave_infl)
matplotlib.pyplot.show(ave_plot)
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:
In [ ]:
max_plot = matplotlib.pyplot.plot(p_data.max(axis=0))
matplotlib.pyplot.show(max_plot)
In [ ]:
min_plot = matplotlib.pyplot.plot(p_data.min(axis=0))
matplotlib.pyplot.show(min_plot)
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.
The function matplotlib.pyplot.figure()
creates a space into which we will place all of our plots.
The parameter 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.
Each 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:
In [ ]:
import numpy
import matplotlib.pyplot
data = numpy.loadtxt(fname='data/inflammation-01.csv', delimiter=',')
fig = matplotlib.pyplot.figure(figsize=(10.0, 3.0))
axes1 = fig.add_subplot(1, 3, 1)
axes2 = fig.add_subplot(1, 3, 2)
axes3 = fig.add_subplot(1, 3, 3)
axes1.set_ylabel('average')
axes1.plot(data.mean(axis=0))
axes2.set_ylabel('max')
axes2.plot(data.max(axis=0))
axes3.set_ylabel('min')
axes3.plot(data.min(axis=0))
fig.tight_layout()
matplotlib.pyplot.show(fig)
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.