Python quick start - Part 2

What we have seen in the first part of this quick start can be made easier. Ipython has the option to import when it starts many useful packages for numerical and scientific computing so they are ready for you to use. To use this options you need to start ipython with the command:

ipython --pylab

Using this option numpy as matplotlib are a already imported and ready to use.

Reading files

A common task when working with measurements is to read a file in order to process and visuallise some data. Lets suppose that you need to open a text file (“measurements.txt”) that contains columns of numerical data:

1    23.4
2    43.8
3    55.1

You can read this file using the loadtxt command from numpy:

>>> m = loadtxt("measurements.txt")

Note

Remember that the loadtxt command is available to you, without importing numpy explicitly, because we are using the –pylab option.

The variable m is now an array that contains the numerical data. You can see its contents by simply typing:

>>> print m
# or
>>> m

You can also check its shape by typing:

>>> m.shape
(3,2)

This means that array has three rows and two columns.

An common case is that your text file contains some column titles, for example:

No.  Value
----------
1    23.4
2    43.8
3    55.1

If you try to read such a file as before you will get an error as the loadtxt command expects to find only columns of numbers. You can read this file by writing:

>>> m = loadtxt("measurements.txt", skiprows = 2)

This instructs python to skip the first two rows and start reading columnar data after that.

Array slicing

A very important feature of an array is that you can select the data that you need to access. The following commands will return arrays that hold only the selected subsets of data.

Warning

You need to take care as the numbering of rows and columns starts from 0 and not from 1.

For example you can get these single-element arrays:

>>> a[0,0] # the first row and the first column
1
>>> a[2,1] # third row, second column
55.1

You can select more than one numbers at once using the following notation:

>>> a[0:2, 0]
array([ 1.,  2.])

This returns the rows 0 and 1 from column 0.

You can select a complete axis by simply using ”:”:

>>> a[:,0] # This returns all elements of column 0
array([ 1.,  2.,  3.])
>>> a[1,:] # This returns all elements of row 1
array([  2. ,  43.8])

With these simple notation you can easily access the subset of your data that you need to use.

More on Plotting

Now that we now how to access our data we can try to plot them:

>>> x = a[:,0]
>>> y = a[:,1]
>>> plot(x,y)

(Source code, png, hires.png, pdf)

_images/quick_start_2-1.png

This needs some styling:

>>> xlabel("Measurement number") # add a label for the x axis
>>> ylabel("Value")              # add a label for the y axis
>>> title("My first plot")       # add also a title
>>> grid(True)                   # activate the grid

(Source code, png, hires.png, pdf)

_images/quick_start_2-2.png

You can add another line in the same figure by calling the plot function again. Let’s plot a second line representing the double of our values, i.e. 2*y. We will also change the style of this line in green dashes:

>>> plot(x,2*y, '--g')

(Source code, png, hires.png, pdf)

_images/quick_start_2-3.png

Saving your results

Let’s say now that you after you have read your measurements you have performed some (very useful) calculation and you want to save the result, so you can use it in the future:

>>> result = 1/*y**2 - sin(y)

You can save an array in a text file by using the savetxt command:

>>> savetxt('output.txt', result)

This command will save the array result in a file named output.txt.

Getting help

It is certain that soon (or maybe now) you will forget the option you need to use with loadtxt, or you will forget the order you need to provide the arguments for savetxt (was it the filename first or the array...).

A good way to remember is to use the help within ipython:

>>> loadtxt ?
Load data from a text file.

Each row in the text file must have the same number of values.

Parameters
----------
fname : file or str
    File, filename, or generator to read.  If the filename extension is
    ``.gz`` or ``.bz2``, the file is first decompressed. Note that
    generators should return byte strings for Python 3k.
dtype : data-type, optional
    Data-type of the resulting array; default: float.  If this is a
    record data-type, the resulting array will be 1-dimensional, and
    each row will be interpreted as an element of the array.  In this

In this way you can learn about a function options and details.

Note

You may need to press q in order to exit back to the normal ipython terminal.

An other useful way to learn about the python functions is (ofcourse) the Internet. Here are some links that can help you read more about the functions that you learned in this part of the quick start guide: