You are on page 1of 1

Python & Pylab Cheat Sheet

Running
python
ipython
ipython --pylab
python file.py
python -i file.py

standard python shell.


improved interactive shell.
ipython including pylab
run file.py
run file.py, stay in interactive mode

To quit use exit() or [ctrl]+[d]

Getting Help
interactive Help
help for object
ipython: help for object
ipython: extended help for object
ipython: help on magic commands

help()
help(object)
object?
object??
%magic

Import Syntax, e.g. for


import math
import math as m
from math import pi
from math import *

use:
use:
use:
use:

Integer
Float
Complex
Boolean
String
String

math.pi
m.pi
pi
pi (use sparingly)

with this:
c.real
c.imag
c.conjugate()

1.0
2.0
1-2j

Operators
mathematics
+
addition
subtraction
*
multiplication
i/i int division
i/f float division
** power
%
modulo

comparison
= assign
== equal
!= unequal
< less
<= less-equal
>= greater-equal
> greater

Basic Syntax
raw_input(foo)
class Foo(Object): ...
def bar (args): ...
if c: ... elif c: ... else:
try: ... except Error : ...
while cond: ...
for item in list: ...
[item for item in list]

read string from command-line


class definition
function/method definition
branching
exception handling
while loop
for loop
for loop, list notation

Useful tools
pylint file.py
pydoc file
python -m doctest file.py
python -m pdb file.py

Statistics

The following import statement is assumed:


from pylab import *

sum(l,d) or a.sum(d)
mean(l,d) or a.mean(d)
std(l,d) or a.std(d)
min(l,d) or a.min(d)
max(l,d) or a.max(d)

General Math
f: float, c: complex:
abs(c)
sign(c)
fix(f)
floor(f)
ceil(f)
f.round(p)
angle(c)
sin(c)
arcsin(c)
cos, tan,...

absolute value of f or c
get sign of f or c
round towards 0
round towards inf
round towards + inf
round f to p places
angle of complex number
sinus of argument
arcsin of argument
analogous

Defining Lists, Arrays, Matrices

Types
i = 1
f = 1.
c = 1+2j
True/False
abc
"abc"

NumPy & Friends

static code checker


parse docstring to man-page
run examples in docstring
run in debugger

l: list, a: array:
[[1,2],[3,4,5]]
array([[1,2],[3,4]])
matrix([[1,2],[3,4]])
range(min, max, step)
arange(min, max, step)
frange(min, max, step)
linspace(min, max, num)
meshgrid(x,y)
zeros, ones, eye

basic list
array from rectangular list
matrix from 2d-list
integer list in [min, max)
integer list in [min, max)
float list in [min, max]
num samples in [min, max]
create coord-matrices
generate special arrays

Misc functions
loadtxt(file)
polyval(coeff,xvals)
roots(coeff)
map(func,list)

Plot Types
plot(xvals, yvals, g+)
errorbar()
semilogx(), semilogx()
loglog()
polar(phi_vals, rvals)
hist(vals, n_bins)
bar(low_edge, vals, width)
contour(xvals,yvals,zvals)

List/Array Properties
len(l)
a.size
a.ndim
a.shape
ravel(l) or a.ravel()
a.flat

size of first dim


total number of entries
number of dimensions
size along dimensions
convert to 1-dim
iterate all entries

Matrix Operations
a: array, M: matrix:
a*a
dot(a,a) or M*M
cross(a,a)
inv(a) or M.I
transpose(a) or M.T
det(a)

element-wise product
dot product
cross product
inverted matrix
transposed matrix
calculate determinate

mark 3 points with green +


like plot with error bars
like plot, semi-log axis
double logarithmic plot
plot in polar coordinates
create histogram from values
create bar-plot
create contour-plot

Pylab Plotting Equivalences


figure()

list: basic access


list: range access [min,max)
array: basic access
array: range access [min,max)
array: select indices in list
array: select where cond true

read values from file


evaluate polynomial at xvals
find roots of polynomial
apply func on each element of list

Plotting

Element Access
l[row][col]
l[min:max]
a[row,col] or a[row][col]
a[min:max,min:max]
a[list]
a[np.where(cond)]

sum elements along d


mean along d
standard deviation along d
minima along d
maxima along d

subplot(2,1,1)
plot()
errorbar()
semilogx, ...
polar()
axis()
grid()
title()
xlabel()
legend()
colorbar()

fig = figure()
ax = axes()
ax = fig.add_subplot(2,1,1)
ax.plot()
ax.errorbar()
analogous
axes(polar=True) and ax.plot()
ax.set_xlim(), ax.set_ylim()
ax.grid()
ax.set_title()
ax.set_xlabel()
ax.legend()
fig.colorbar(plot)

Plotting 3D
from mpl_toolkits.mplot3d import Axes3D
ax = fig.add_subplot(...,projection=3d)
or ax = Axes3D(fig)
create 3d-axes object
ax.plot(xvals, yvals, zvals) normal plot in 3d
ax.plot_wireframe
wire mesh
ax.plot_surface
colored surface
License: CC-by-sa
Copyright: January 20, 2014, Nicola Chiapolini
http://www.physik.uzh.ch/nchiapol

You might also like