Python & Pylab Cheat Sheet NumPy & Friends Plotting

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

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

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

Import Syntax, e.g. for

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

Types

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

i = 1 Integer

f = 1. Float

c = 1+2j Complex with this:

True/False Boolean

c.real

1.0

'abc' String

c.imag

2.0

"abc" String

c.conjugate() 1-2j

Operators

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

Basic Syntax

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

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]

Useful tools

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

read string from command-line class definition function/method definition branching exception handling while loop for loop for loop, list notation

static code checker parse docstring to man-page run examples in docstring run in debugger

NumPy & Friends

The following import statement is assumed: from pylab import *

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

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

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

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

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

Statistics

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)

sum elements along d mean along d standard deviation along d minima along d maxima along d

Misc functions

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

read values from file evaluate polynomial at xvals find roots of polynomial apply func on each element of list

Plotting

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)

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

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

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download