User Tools

Site Tools


python_getting_started

A bit of Python

Python is available on any Linux/Unix machine including department machines and Macs.

You can download and install python on your own computer by following instructions at http://www.python.org

You can use the Python interpreter interactively by typing python at a terminal window. Ipython is a nicer front end to python that is invoked with

ipython

To quit, type control-d

To run python code in a file code.py, either type

run code.py

in ipython, or type

python code.py

at the unix command line.

When in ipython, you may type python statements or expressions that are evaluated, or ipython commands. See the Video tutorial on using ipython, in five parts by Jeff Rush, for help getting started with ipython.

Documentation is immediately available for many things. For example:

> ipython
asa:~$ ipython 
Python 2.7.3 (v2.7.3:70274d53c1dd, Apr  9 2012, 20:52:43) 
Type "copyright", "credits" or "license" for more information.

IPython 0.13.2 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: list?
Type:		type
Base Class:	<type 'type'>
String Form:	<type 'list'>
Namespace:	Python builtin
Docstring:
    list() -> new list
    list(sequence) -> new list initialized from sequence's items

In [2]: help(list)
Help on class list in module __builtin__:

class list(object)
 |  list() -> new list
 |  list(sequence) -> new list initialized from sequence's items
 |  
 |  Methods defined here:
   .
   .
   .
 |  append(...)
 |      L.append(object) -- append object to end
 |  
   .
   .
   .
 |  
 |  sort(...)
 |      L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
 |      cmp(x, y) -> -1, 0, 1

What is the value of $(100\cdot 2 - 12^2) / 7 \cdot 5 + 2\;\;\;$?

  In [301]: (100*2 - 12**2) / 7*5 + 2
  Out[301]: 42

In order to compute something like $\sin(\pi/2)$ we first need to import the math module:

In [303]: import math
In [304]: math.sin(math.pi/2)
1.0

How do I find out what other mathematical functions are available?

help("math")

Plotting

Let's get on to that all important step of visualizing data. We will be using the matplotlib Python package for that. Let's start by plotting the function $f(x) = x^2$.

First, let's generate the numbers. Well, there are tons of ways to do so. First, using afor loop.

In [3]: f = []
 
In [4]: for i in range(10) :
   ...:     f.append(i**2)
   ...:     
 
In [5]: f
Out[5]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

To plot the data, first import the pyplot module.

In [6]: import matplotlib.pyplot as plt
 
In [7]: plt.plot(range(10), f)
Out[7]: [<matplotlib.lines.Line2D at 0x10549b590>]

In order to actually see the plot you need to do:

In [8]: plt.show()

As an alternative, you can put matplotlib in interactive mode before plotting using the command plt.ion().

Python has some nifty syntax for generating lists. Watch this! A list comprehension!!

In [9]: f = [i**2 for i in range(10)]
 
In [10]: f
Out[10]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

There's an alternative way of doing this using numpy:

In [11]: import numpy as np
 
In [12]: f = np.arange(10)**2
 
In [13]: f
Out[13]: array([ 0,  1,  4,  9, 16, 25, 36, 49, 64, 81])

Note that plotting functions to accept either lists or numpy arrays, so a fast way of doing our plot is

In [14]: plt.plot(np.arange(10), np.arange(10)**2)

For a smoother plot:

In [14]: x = np.arange(10, 0.1)
 
In [15]: plt.plot(x, x**2, 'ob')
Out[15]: [<matplotlib.lines.Line2D at 0x1054162d0>]

We can add a second plot to the same axes by calling plot again:

In [16]: plt.plot(x, x, 'dr')
Out[16]: [<matplotlib.lines.Line2D object at 0x3608990>]

Matrices in Python

Can I work with vectors and matrices in python?

Of course! No data analysis tool is worth the bytes it burns if it doesn't. The numpy package provides the required magic. Let's create an array that represents the following matrix: \[\left ( \begin{array}{cc} 1 & 2\\ 3 & 4\\ 5 & 6 \end{array} \right ) \] by doing

In [17]: import numpy as np

In [18]: m = np.array([[1,2], [3,4], [5,6]])

In [19]: m
Out[19]: 
array([[1, 2],
       [3, 4],
       [5, 6]])

Let's construct the matrices \[a = \left ( \begin{array}{cc} 2 & 2 & 2\\ 2 & 2 & 2\\ 2 & 2 & 2 \end{array} \right ) \] and \[b = \left ( \begin{array}{cc} 1 & 2 & 3\\ 4 & 5 & 6\\ 7 & 8 & 9 \end{array} \right ) \]

In [16]: a = np.ones((3,3)) * 2
 
In [17]: a
Out[17]: 
array([[ 2.,  2.,  2.],
       [ 2.,  2.,  2.],
       [ 2.,  2.,  2.]])
 
In [18]: b = np.resize(np.arange(9)+1,(3,3))
 
In [19]: b
Out[19]: 
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

What is the value of $a * b$?

In [20]: a * b
Out[21]: 
array([[ 2,  4,  6],
       [ 8, 10, 12],
       [14, 16, 18]])

The * operator does a component-wise multiplication. Use the numpy function dot to do matrix multiplication.

In [22]: np.dot(a,b)
Out[22]: 
array([[24, 30, 36],
       [24, 30, 36],
       [24, 30, 36]])

An array is transposed by

In [23]: b.transpose()
Out[23]: 
array([[1, 4, 7],
       [2, 5, 8],
       [3, 6, 9]])
 
In [24]: b.T
Out[24]: 
array([[1, 4, 7],
       [2, 5, 8],
       [3, 6, 9]])

Elements and sub-matrices are easily extracted:

In [25]: b
Out[25]: 
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
 
In [26]: b[0,0]
Out[26]: 1
 
In [27]: b[0,1]
Out[27]: 2
 
In [28]: b[0:2, 1:3]
Out[28]: 
array([[2, 3],
       [5, 6]])

Let's multiply the first row of a $a$ by the second column of $b$.

In [29]: np.dot(a[0], b[:,1])
Out[29]: 30.0
 
In [30]: np.dot(a[0],b.T[1])
Out[30]: 30.0

How do I find the inverse of a matrix?

In [2]: z = np.array([[2,1,1],[1,2,2],[2,3,4]])
 
In [3]: z
Out[3]: 
array([[2, 1, 1],
       [1, 2, 2],
       [2, 3, 4]])
 
In [4]: np.linalg.inv(z)
Out[4]: 
array([[ 0.66666667, -0.33333333,  0.        ],
       [ 0.        ,  2.        , -1.        ],
       [-0.33333333, -1.33333333,  1.        ]])
 
In [5]: np.dot(z, np.linalg.inv(z))
Out[5]: 
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])
python_getting_started.txt ยท Last modified: 2016/08/02 14:47 (external edit)