Você está na página 1de 1

Python & Pylab Cheat Sheet

Running
python ipython ipython --pylab python le.py python -i le.py standard python shell. improved interactive shell. ipython including pylab run le.py run le.py, stay in interactive mode

NumPy & Friends


The following import statement is assumed: from pylab import *

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

General Math
f: oat, 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

Misc functions
loadtxt(le ) polyval(coeff,xvals) roots(coeff) map(func ,list ) read values from le evaluate polynomial at xvals nd roots of polynomial apply func on each element of list

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

Getting Help
help() help(object ) object ? object ?? %magic import math import math as m from math import pi from math import * interactive Help help for object ipython: help for object ipython: extended help for object ipython: help on magic commands use: use: use: use: math.pi m.pi pi pi (use sparingly)

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

Import Syntax, e.g. for

Dening 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) oat list in [min, max] num samples in [min, max] create coord-matrices generate special arrays

Types
i = 1 f = 1. c = 1+2j True/False abc "abc" Integer Float Complex Boolean String String

with this: c.real c.imag c.conjugate() comparison = assign == equal != unequal < less <= less-equal >= greater-equal > greater

1.0 2.0 1-2j

Pylab Plotting Equivalences


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

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

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 subplot(2,1,1) plot() errorbar() semilogx, ... polar() axis() grid() title() xlabel() legend() colorbar()

List/Array Properties
len(l) a.size a.ndim a.shape ravel(l) or a.ravel() a.flat size of rst dim total number of entries number of dimensions size along dimensions convert to 1-dim iterate all entries

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 denition function/method denition 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

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

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

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

Você também pode gostar