Python 1 - Introduction to Python


Learning Objectives

  • Get used to the IPython Notebook.
  • Understand what a library is and how to use it.
  • Read tabular data from a file into a program.
  • Assign values to variables.
  • Select individual values and subsections from data.
  • Perform operations on arrays of data.
  • Display simple graphs.

IPython Notebook

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:

  • crtl + enter - Run the contents of this cell
  • B - moves out from inside this cell and selects the entire cell
  • esc - moves from this window to select the whole box
  • enter - will move you back in
  • M - changes the whole box to markdown
  • Y - changes the whole box to code

Libraries

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]:
 

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]:
 

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.

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 [ ]:
 

Variables

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

In [12]:
 

Reassign them

In [ ]:
 

Do some fancy printing with them, throwing in a bit of string usage too.

Print Formatting


We use `.format` at the end of a string to insert variables which are not strings into a string. If we have multiple items to insert then we use `{0}, {1}, {2}... etc` and order them accordinglt in the format `()`.
In [ ]:
 

We can also use variables to define other variables

In [ ]:
 

and then we can change the temperature in Kelvin

In [ ]:
 

Note that changing the temperature in Kelvin does not change the previous temperature we used to calculate it in the first place

In [ ]:
 

Tip


You can use the `%whos` command at any time to see what variables you have created and what modules you have loaded into the computers memory. As this is an IPython command, it will only work if you are in an IPython terminal or the Jupyter Notebook.
In [ ]:
 

Arrays

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.

In [10]:
 

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 [ ]:
 

Indexing


What may also surprise you is that when Python displays an array, it shows the element with index [0, 0] in the upper left corner rather than the lower left. This is consistent with the way mathematicians draw matrices, but different from the Cartesian coordinates. The indices are (row, column) instead of (column, row) for the same reason, which can be confusing when plotting data.

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 [ ]:
 

and p_data[15,:] gives us the 15 row. The : says give me all the elements in this domain.

In [ ]:
 

Thus we can make the domain smaller and essentially crop the array. By using the colon between the two limits:

In [ ]:
 

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 [ ]:
 

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 [ ]:
 

Arrays and Statistics

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 [ ]:
 

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 [ ]:
 

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 [ ]:
 

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 [ ]:
 

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 [ ]:
 

As a quick check, we can ask this array what its shape is:

In [ ]:
 

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 [ ]:
 

which is the average inflammation per patient across all days.

Matplotlib

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:

Inline with IPythonNB


If you’re using an IPython / Jupyter notebook, you’ll need to execute the following command in order for your matplotlib images to appear in the notebook when `show()` is called: `% matplotlib inline` The `%` indicates an IPython magic function - a function that is only valid within the notebook environment. Note that you only have to execute this function once per notebook.
In [ ]:
 

Let’s take a look at the average inflammation over time:

In [ ]:
 

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 [ ]:
 
In [ ]:
 

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.

Subplots

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 [ ]:
 

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.)

Scientists dislike typing


We will always use the syntax `import numpy` to import NumPy. However, in order to save typing, it is often suggested to make a shortcut like so: `import numpy as np`. If you ever see Python code online using a NumPy function with `np` (for example, `np.loadtxt(...)`), it’s because they’ve used this shortcut.

Make your own plot


What does the following program print out?
first, second = 'Grace', 'Hopper'
third, fourth = second, first
print third, fourth

Slicing strings


A section of an array is called a slice. We can take slices of character strings as well:
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.

Thin Slices


The expression element[3:3] produces an empty string, i.e., a string that contains no characters. If data holds our array of patient data, what does data[3:3, 4:4] produce? What about data[3:3, :]?

Check your understanding: plot scaling


Why do all of our plots stop just short of the upper end of our graph?

Check your understanding: drawing straight lines


Why are the vertical lines in our plot of the minimum inflammation per day not perfectly vertical?

Make your own plot


Create a plot showing the standard deviation (`numpy.std`) of the inflammation data for each day across all patients.

Moving plots around


Modify the program to display the three plots on top of one another instead of side by side.