From fb4b7ebb335101c5355d4169dc4fa99388bffeeb Mon Sep 17 00:00:00 2001 From: MMesch Date: Thu, 21 Apr 2016 16:53:16 +0200 Subject: [PATCH 01/96] Create gh-pages branch via GitHub --- index.html | 438 +++++++++++++++++++++++++++++++++++ params.json | 6 + stylesheets/github-light.css | 124 ++++++++++ stylesheets/normalize.css | 424 +++++++++++++++++++++++++++++++++ stylesheets/stylesheet.css | 245 ++++++++++++++++++++ 5 files changed, 1237 insertions(+) create mode 100644 index.html create mode 100644 params.json create mode 100644 stylesheets/github-light.css create mode 100644 stylesheets/normalize.css create mode 100644 stylesheets/stylesheet.css diff --git a/index.html b/index.html new file mode 100644 index 0000000..cea306a --- /dev/null +++ b/index.html @@ -0,0 +1,438 @@ + + + + + Scientific python cheat sheet by IPGP + + + + + + + + + +
+

+Scientific Python Cheatsheet

+ + + +

Table of Contents

+ + + + + +

+Pure Python

+ +

+Types

+ +
a = 2           # integer
+b = 5.0         # float
+c = 8.3e5       # exponential
+d = 1.5 + 0.5j  # complex
+e = 3 > 4       # boolean
+f = 'word'      # string
+ +

+Lists

+ +
a = ['red', 'blue', 'green']      # manually initialization
+b = range(5)                      # initialization through a function
+c = [nu**2 for nu in b]           # initialize through list comprehension
+d = [nu**2 for nu in b if b < 3]  # list comprehension withcondition
+e = c[0]                          # access element
+f = e[1: 2]                       # access a slice of the list
+g = ['re', 'bl'] + ['gr']         # list concatenation
+h = ['re'] * 5                    # repeat a list
+['re', 'bl'].index('re')          # returns index of 're'
+'re' in ['re', 'bl']              # true if 're' in list
+sorted([3, 2, 1])                 # returns sorted list
+z = ['red'] + ['green', 'blue']   # list concatenation
+ +

+Dictionaries

+ +
a = {'red': 'rouge', 'blue': 'bleu', 'green': 'vert'}  # dictionary
+b = a['red']                                           # translate item
+c = [value for key, value in b.items()]                # loop through contents
+d = a.get('yellow', 'no translation found')            # return default
+ +

+Strings

+ +
a = 'red'                      # assignment
+char = a[2]                    # access individual characters
+'red ' + 'blue'                # string concatenation
+'1, 2, three'.split(',')       # split string into list
+'.'.join(['1', '2', 'three'])  # concatenate list into string
+ +

+Operators

+ +
a = 2             # assignment
+a += 1 (*=, /=)   # change and assign
+3 + 2             # addition
+3 / 2             # integer division (python2) or float division (python3)
+3 // 2            # integer division
+3 * 2             # multiplication
+3 ** 2            # exponent
+3 % 2             # remainder
+abs()             # absolute value
+1 == 1            # equal
+2 > 1             # larger
+2 < 1             # smaller
+1 != 2            # not equal
+1 != 2 and 2 < 3  # logical AND
+1 != 2 or 2 < 3   # logical OR
+not 1 == 2        # logical NOT
+a in b            # test if a is in b
+a is b            # test if objects point to the same memory (id)
+ +

+Control Flow

+ +

+if/elif/else

+ +
a, b = 1, 2
+if a + b == 3:
+    print 'True'
+elif a + b == 1:
+    print 'False'
+else:
+    print '?'
+ +

+for

+ +
a = ['red', 'blue',
+     'green']
+for color in a:
+    print color
+ +

+while

+ +
number = 1
+while number < 10:
+    print number
+    number += 1
+ +

+break

+ +
number = 1
+while True:
+    print number
+    number += 1
+    if number > 10:
+        break
+ +

+continue

+ +
for i in range(20):
+    if i % 2 == 0:
+        continue
+    print i
+ +

+Functions, Classes, Generators, Decorators

+ +

+Function

+ +
def myfunc(a1, a2):
+    return x
+
+x = my_function(a1,a2)
+ +

+Class

+ +
class Point(object):
+    def __init__(self, x):
+        self.x = x
+    def __call__(self):
+        print self.x
+
+x = Point(3)
+ +

+Generators

+ +
def firstn(n):
+    num = 0
+    while num < n:
+        yield num
+        num += 1
+
+x = [for i in firstn(10)]
+ +

+Decorators

+ +
class myDecorator(object):
+    def __init__(self, f):
+        self.f = f
+    def __call__(self):
+        print "call"
+        self.f()
+
+@myDecorator
+def my_funct():
+    print 'func'
+
+my_func()
+ +

+NumPy

+ +

+array initialization

+ +
np.array([2, 3, 4])             # direct initialization
+np.empty(20, dtype=np.float32)  # single precision array with 20 entries
+np.zeros(200)                   # initialize 200 zeros
+np.ones((3,3), dtype=np.int32)  # 3 x 3 integer matrix with ones
+np.eye(200)                     # ones on the diagonal
+np.zeros_like(a)                # returns array with zeros and the shape of a
+np.linspace(0., 10., 100)       # 100 points from 0 to 10
+np.arange(0, 100, 2)            # points from 0 to <100 with step width 2
+np.logspace(-5, 2, 100)         # 100 log-spaced points between 1e-5 and 1e2
+np.copy(a)                      # copy array to new memory
+ +

+reading/ writing files

+ +
np.fromfile(fname/object, dtype=np.float32, count=5)  # read binary data from file
+np.loadtxt(fname/object, skiprows=2, delimiter=',')   # read ascii data from file
+ +

+array properties and operations

+ +
a.shape                # a tuple with the lengths of each axis
+len(a)                 # length of axis 0
+a.ndim                 # number of dimensions (axes)
+a.sort(axis=1)         # sort array along axis
+a.flatten()            # collapse array to one dimension
+a.conj()               # return complex conjugate
+a.astype(np.int16)     # cast to integer
+np.argmax(a, axis=2)   # return index of maximum along a given axis
+np.cumsum(a)           # return cumulative sum
+np.any(a)              # True if any element is True
+np.all(a)              # True if all elements are True
+np.argsort(a, axis=1)  # return sorted index array along axis
+ +

+indexing

+ +
a = np.arange(100)          # initialization with 0 - 99
+a[: 3] = 0                  # set the first three indices to zero
+a[1: 5] = 1                 # set indices 1-4 to 1
+a[start:stop:step]          # general form of indexing/slicing
+a[None, :]                  # transform to column vector
+a[[1, 1, 3, 8]]             # return array with values of the indices
+a = a.reshape(10, 10)       # transform to 10 x 10 matrix
+a.T                         # return transposed view
+np.transpose(a, (2, 1, 0))  # transpose array to new axis order
+a[a < 2]                    # returns array that fulfills elementwise condition
+ +

+boolean arrays

+ +
a < 2                          # returns array with boolean values
+np.logical_and(a < 2, b > 10)  # elementwise logical and
+np.logical_or(a < 2, b > 10)   # elementwise logical or
+~a                             # invert boolean array
+np.invert(a)                   # invert boolean array
+ +

+elementwise operations and math functions

+ +
a * 5              # multiplication with scalar
+a + 5              # addition with scalar
+a + b              # addition with array b
+a / b              # division with b (np.NaN for division by zero)
+np.exp(a)          # exponential (complex and real)
+np.sin(a)          # sine
+np.cos(a)          # cosine
+np.arctan2(y,x)    # arctan(y/x)
+np.arcsin(x)       # arcsin
+np.radians(a)      # degrees to radians
+np.degrees(a)      # radians to degrees
+np.var(a)          # variance of array
+np.std(a, axis=1)  # standard deviation
+ +

+inner / outer products

+ +
np.dot(a, b)                        # inner matrix product: a_mi b_in
+np.einsum('ijkl,klmn->ijmn', a, b)  # einstein summation convention
+np.sum(a, axis=1)                   # sum over axis 1
+np.abs(a)                           # return array with absolute values
+a[None, :] + b[:, None]             # outer sum
+a[None, :] * b[None, :]             # outer product
+np.outer(a, b)                      # outer product
+np.sum(a * a.T)                     # matrix norm
+ +

+interpolation, integration

+ +
np.trapz(y, x=x, axis=1)  # integrate along axis 1
+np.interp(x, xp, yp)      # interpolate function xp, yp at points x
+ +

+fft

+ +
np.fft.fft(y)             # complex fourier transform of y
+np.fft.fftfreqs(len(y))   # fft frequencies for a given length
+np.fft.fftshift(freqs)    # shifts zero frequency to the middle
+np.fft.rfft(y)            # real fourier transform of y
+np.fft.rfftfreqs(len(y))  # real fft frequencies for a given length
+ +

+rounding

+ +
np.ceil(a)   # rounds to nearest upper int
+np.floor(a)  # rounds to nearest lower int
+np.round(a)  # rounds to neares int
+ +

+random variables

+ +
np.random.normal(loc=0, scale=2, size=100)  # 100 normal distributed random numbers
+np.random.seed(23032)                       # resets the seed value
+np.random.rand(200)                         # 200 random numbers in [0, 1)
+np.random.uniform(1, 30, 200)               # 200 random numbers in [1, 30)
+np.random.random_integers(1, 15, 300)       # 300 random integers between [1, 15]
+ +

+Matplotlib

+ +

+figures and axes

+ +
fig = plt.figure(figsize=(5, 2), facecolor='black')  # initialize figure
+ax = fig.add_subplot(3, 2, 2)                        # add second subplot in a 3 x 2 grid
+fig, axes = plt.subplots(5, 2, figsize=(5, 5))       # return fig and array of axes in a 5 x 2 grid
+ax = fig.add_axes([left, bottom, width, height])     # manually add axes at a certain position
+ +

+figures and axes properties

+ +
fig.suptitle('title')            # big figure title
+fig.subplots_adjust(bottom=0.1, right=0.8, top=0.9, wspace=0.2,
+                    hspace=0.5)  # adjust subplot positions
+fig.tight_layout(pad=0.1,h_pad=0.5, w_pad=0.5, rect=None) # adjust
+subplots to fit perfectly into fig
+ax.set_xlabel()                  # set xlabel
+ax.set_ylabel()                  # set ylabel
+ax.set_xlim(1, 2)                # sets x limits
+ax.set_ylim(3, 4)                # sets y limits
+ax.set_title('blabla')           # sets the axis title
+ax.set(xlabel='bla')             # set multiple parameters at once
+ax.legend(loc='upper center')    # activate legend
+ax.grid(True, which='both')      # activate grid
+bbox = ax.get_position()         # returns the axes bounding box
+bbox.x0 + bbox.width             # bounding box parameters
+ +

+plotting routines

+ +
ax.plot(x,y, '-o', c='red', lw=2, label='bla')  # plots a line
+ax.scatter(x,y, s=20, c=color)                  # scatter plot
+ax.pcolormesh(xx,yy,zz, shading='gouraud')      # fast colormesh function
+ax.colormesh(xx,yy,zz, norm=norm)               # slower colormesh function
+ax.contour(xx,yy,zz, cmap='jet')                # contour line plot
+ax.contourf(xx,yy,zz, vmin=2, vmax=4)           # filled contours plot
+n, bins, patch = ax.hist(x, 50)                 # histogram
+ax.imshow(matrix, origin='lower', extent=(x1, x2, y1, y2))  # show image
+ax.specgram(y, FS=0.1, noverlap=128, scale='linear')  # plot a spectrogram
+ + + +
+ + + + diff --git a/params.json b/params.json new file mode 100644 index 0000000..00e3151 --- /dev/null +++ b/params.json @@ -0,0 +1,6 @@ +{ + "name": "Scientific python cheat sheet", + "tagline": "simple overview of python, numpy, scipy, matplotlib functions that are useful for scientific work", + "body": "Scientific Python Cheatsheet\r\n============================\r\n\r\n\r\n**Table of Contents**\r\n\r\n- [Scientific Python Cheatsheet](#scientific-python-cheatsheet)\r\n - [Pure Python](#pure-python)\r\n - [Types](#types)\r\n - [Lists](#lists)\r\n - [Dictionaries](#dictionaries)\r\n - [Strings](#strings)\r\n - [Operators](#operators)\r\n - [Control Flow](#control-flow)\r\n - [if/elif/else](#ifelifelse)\r\n - [for](#for)\r\n - [while](#while)\r\n - [break](#break)\r\n - [continue](#continue)\r\n - [Functions, Classes, Generators, Decorators](#functions-classes-generators-decorators)\r\n - [Function](#function)\r\n - [Class](#class)\r\n - [Generators](#generators)\r\n - [Decorators](#decorators)\r\n - [NumPy](#numpy)\r\n - [array initialization](#array-initialization)\r\n - [reading/ writing files](#reading-writing-files)\r\n - [array properties and operations](#array-properties-and-operations)\r\n - [indexing](#indexing)\r\n - [boolean arrays](#boolean-arrays)\r\n - [elementwise operations and math functions](#elementwise-operations-and-math-functions)\r\n - [inner / outer products](#inner--outer-products)\r\n - [interpolation, integration](#interpolation-integration)\r\n - [fft](#fft)\r\n - [rounding](#rounding)\r\n - [random variables](#random-variables)\r\n - [Matplotlib](#matplotlib)\r\n - [figures and axes](#figures-and-axes)\r\n - [figures and axes properties](#figures-and-axes-properties)\r\n - [plotting routines](#plotting-routines)\r\n\r\n\r\n\r\nPure Python\r\n-----------\r\n\r\n### Types\r\n```python\r\na = 2 # integer\r\nb = 5.0 # float\r\nc = 8.3e5 # exponential\r\nd = 1.5 + 0.5j # complex\r\ne = 3 > 4 # boolean\r\nf = 'word' # string\r\n```\r\n\r\n### Lists\r\n\r\n```python\r\na = ['red', 'blue', 'green'] # manually initialization\r\nb = range(5) # initialization through a function\r\nc = [nu**2 for nu in b] # initialize through list comprehension\r\nd = [nu**2 for nu in b if b < 3] # list comprehension withcondition\r\ne = c[0] # access element\r\nf = e[1: 2] # access a slice of the list\r\ng = ['re', 'bl'] + ['gr'] # list concatenation\r\nh = ['re'] * 5 # repeat a list\r\n['re', 'bl'].index('re') # returns index of 're'\r\n're' in ['re', 'bl'] # true if 're' in list\r\nsorted([3, 2, 1]) # returns sorted list\r\nz = ['red'] + ['green', 'blue'] # list concatenation\r\n```\r\n\r\n### Dictionaries\r\n\r\n```python\r\na = {'red': 'rouge', 'blue': 'bleu', 'green': 'vert'} # dictionary\r\nb = a['red'] # translate item\r\nc = [value for key, value in b.items()] # loop through contents\r\nd = a.get('yellow', 'no translation found') # return default\r\n```\r\n\r\n### Strings\r\n\r\n```python\r\na = 'red' # assignment\r\nchar = a[2] # access individual characters\r\n'red ' + 'blue' # string concatenation\r\n'1, 2, three'.split(',') # split string into list\r\n'.'.join(['1', '2', 'three']) # concatenate list into string\r\n```\r\n\r\n### Operators\r\n\r\n```python\r\na = 2 # assignment\r\na += 1 (*=, /=) # change and assign\r\n3 + 2 # addition\r\n3 / 2 # integer division (python2) or float division (python3)\r\n3 // 2 # integer division\r\n3 * 2 # multiplication\r\n3 ** 2 # exponent\r\n3 % 2 # remainder\r\nabs() # absolute value\r\n1 == 1 # equal\r\n2 > 1 # larger\r\n2 < 1 # smaller\r\n1 != 2 # not equal\r\n1 != 2 and 2 < 3 # logical AND\r\n1 != 2 or 2 < 3 # logical OR\r\nnot 1 == 2 # logical NOT\r\na in b # test if a is in b\r\na is b # test if objects point to the same memory (id)\r\n```\r\n\r\n### Control Flow\r\n\r\n#### if/elif/else\r\n```python\r\na, b = 1, 2\r\nif a + b == 3:\r\n print 'True'\r\nelif a + b == 1:\r\n print 'False'\r\nelse:\r\n print '?'\r\n```\r\n\r\n#### for\r\n\r\n```python\r\na = ['red', 'blue',\r\n 'green']\r\nfor color in a:\r\n print color\r\n```\r\n\r\n#### while\r\n\r\n```python\r\nnumber = 1\r\nwhile number < 10:\r\n print number\r\n number += 1\r\n```\r\n\r\n#### break\r\n```python\r\nnumber = 1\r\nwhile True:\r\n print number\r\n number += 1\r\n if number > 10:\r\n break\r\n```\r\n\r\n#### continue\r\n\r\n```python\r\nfor i in range(20):\r\n if i % 2 == 0:\r\n continue\r\n print i\r\n```\r\n\r\n### Functions, Classes, Generators, Decorators\r\n\r\n#### Function\r\n```python\r\ndef myfunc(a1, a2):\r\n return x\r\n\r\nx = my_function(a1,a2)\r\n```\r\n\r\n#### Class\r\n```python\r\nclass Point(object):\r\n def __init__(self, x):\r\n self.x = x\r\n def __call__(self):\r\n print self.x\r\n\r\nx = Point(3)\r\n```\r\n\r\n#### Generators\r\n```python\r\ndef firstn(n):\r\n num = 0\r\n while num < n:\r\n yield num\r\n num += 1\r\n\r\nx = [for i in firstn(10)]\r\n```\r\n\r\n#### Decorators\r\n```python\r\nclass myDecorator(object):\r\n def __init__(self, f):\r\n self.f = f\r\n def __call__(self):\r\n print \"call\"\r\n self.f()\r\n\r\n@myDecorator\r\ndef my_funct():\r\n print 'func'\r\n\r\nmy_func()\r\n```\r\n\r\n## NumPy\r\n\r\n### array initialization\r\n\r\n```python\r\nnp.array([2, 3, 4]) # direct initialization\r\nnp.empty(20, dtype=np.float32) # single precision array with 20 entries\r\nnp.zeros(200) # initialize 200 zeros\r\nnp.ones((3,3), dtype=np.int32) # 3 x 3 integer matrix with ones\r\nnp.eye(200) # ones on the diagonal\r\nnp.zeros_like(a) # returns array with zeros and the shape of a\r\nnp.linspace(0., 10., 100) # 100 points from 0 to 10\r\nnp.arange(0, 100, 2) # points from 0 to <100 with step width 2\r\nnp.logspace(-5, 2, 100) # 100 log-spaced points between 1e-5 and 1e2\r\nnp.copy(a) # copy array to new memory\r\n```\r\n\r\n### reading/ writing files\r\n\r\n```python\r\nnp.fromfile(fname/object, dtype=np.float32, count=5) # read binary data from file\r\nnp.loadtxt(fname/object, skiprows=2, delimiter=',') # read ascii data from file\r\n```\r\n\r\n### array properties and operations\r\n\r\n```python\r\na.shape # a tuple with the lengths of each axis\r\nlen(a) # length of axis 0\r\na.ndim # number of dimensions (axes)\r\na.sort(axis=1) # sort array along axis\r\na.flatten() # collapse array to one dimension\r\na.conj() # return complex conjugate\r\na.astype(np.int16) # cast to integer\r\nnp.argmax(a, axis=2) # return index of maximum along a given axis\r\nnp.cumsum(a) # return cumulative sum\r\nnp.any(a) # True if any element is True\r\nnp.all(a) # True if all elements are True\r\nnp.argsort(a, axis=1) # return sorted index array along axis\r\n```\r\n\r\n### indexing\r\n\r\n```python\r\na = np.arange(100) # initialization with 0 - 99\r\na[: 3] = 0 # set the first three indices to zero\r\na[1: 5] = 1 # set indices 1-4 to 1\r\na[start:stop:step] # general form of indexing/slicing\r\na[None, :] # transform to column vector\r\na[[1, 1, 3, 8]] # return array with values of the indices\r\na = a.reshape(10, 10) # transform to 10 x 10 matrix\r\na.T # return transposed view\r\nnp.transpose(a, (2, 1, 0)) # transpose array to new axis order\r\na[a < 2] # returns array that fulfills elementwise condition\r\n```\r\n\r\n### boolean arrays\r\n\r\n```python\r\na < 2 # returns array with boolean values\r\nnp.logical_and(a < 2, b > 10) # elementwise logical and\r\nnp.logical_or(a < 2, b > 10) # elementwise logical or\r\n~a # invert boolean array\r\nnp.invert(a) # invert boolean array\r\n```\r\n\r\n### elementwise operations and math functions\r\n\r\n```python\r\na * 5 # multiplication with scalar\r\na + 5 # addition with scalar\r\na + b # addition with array b\r\na / b # division with b (np.NaN for division by zero)\r\nnp.exp(a) # exponential (complex and real)\r\nnp.sin(a) # sine\r\nnp.cos(a) # cosine\r\nnp.arctan2(y,x) # arctan(y/x)\r\nnp.arcsin(x) # arcsin\r\nnp.radians(a) # degrees to radians\r\nnp.degrees(a) # radians to degrees\r\nnp.var(a) # variance of array\r\nnp.std(a, axis=1) # standard deviation\r\n```\r\n\r\n### inner / outer products\r\n\r\n```python\r\nnp.dot(a, b) # inner matrix product: a_mi b_in\r\nnp.einsum('ijkl,klmn->ijmn', a, b) # einstein summation convention\r\nnp.sum(a, axis=1) # sum over axis 1\r\nnp.abs(a) # return array with absolute values\r\na[None, :] + b[:, None] # outer sum\r\na[None, :] * b[None, :] # outer product\r\nnp.outer(a, b) # outer product\r\nnp.sum(a * a.T) # matrix norm\r\n```\r\n\r\n### interpolation, integration\r\n\r\n```python\r\nnp.trapz(y, x=x, axis=1) # integrate along axis 1\r\nnp.interp(x, xp, yp) # interpolate function xp, yp at points x\r\n```\r\n\r\n### fft\r\n\r\n```python\r\nnp.fft.fft(y) # complex fourier transform of y\r\nnp.fft.fftfreqs(len(y)) # fft frequencies for a given length\r\nnp.fft.fftshift(freqs) # shifts zero frequency to the middle\r\nnp.fft.rfft(y) # real fourier transform of y\r\nnp.fft.rfftfreqs(len(y)) # real fft frequencies for a given length\r\n```\r\n\r\n### rounding\r\n\r\n```python\r\nnp.ceil(a) # rounds to nearest upper int\r\nnp.floor(a) # rounds to nearest lower int\r\nnp.round(a) # rounds to neares int\r\n```\r\n\r\n### random variables\r\n\r\n```python\r\nnp.random.normal(loc=0, scale=2, size=100) # 100 normal distributed random numbers\r\nnp.random.seed(23032) # resets the seed value\r\nnp.random.rand(200) # 200 random numbers in [0, 1)\r\nnp.random.uniform(1, 30, 200) # 200 random numbers in [1, 30)\r\nnp.random.random_integers(1, 15, 300) # 300 random integers between [1, 15]\r\n```\r\n\r\n## Matplotlib\r\n\r\n### figures and axes\r\n\r\n```python\r\nfig = plt.figure(figsize=(5, 2), facecolor='black') # initialize figure\r\nax = fig.add_subplot(3, 2, 2) # add second subplot in a 3 x 2 grid\r\nfig, axes = plt.subplots(5, 2, figsize=(5, 5)) # return fig and array of axes in a 5 x 2 grid\r\nax = fig.add_axes([left, bottom, width, height]) # manually add axes at a certain position\r\n```\r\n\r\n### figures and axes properties\r\n\r\n```python\r\nfig.suptitle('title') # big figure title\r\nfig.subplots_adjust(bottom=0.1, right=0.8, top=0.9, wspace=0.2,\r\n hspace=0.5) # adjust subplot positions\r\nfig.tight_layout(pad=0.1,h_pad=0.5, w_pad=0.5, rect=None) # adjust\r\nsubplots to fit perfectly into fig\r\nax.set_xlabel() # set xlabel\r\nax.set_ylabel() # set ylabel\r\nax.set_xlim(1, 2) # sets x limits\r\nax.set_ylim(3, 4) # sets y limits\r\nax.set_title('blabla') # sets the axis title\r\nax.set(xlabel='bla') # set multiple parameters at once\r\nax.legend(loc='upper center') # activate legend\r\nax.grid(True, which='both') # activate grid\r\nbbox = ax.get_position() # returns the axes bounding box\r\nbbox.x0 + bbox.width # bounding box parameters\r\n```\r\n\r\n### plotting routines\r\n\r\n```python\r\nax.plot(x,y, '-o', c='red', lw=2, label='bla') # plots a line\r\nax.scatter(x,y, s=20, c=color) # scatter plot\r\nax.pcolormesh(xx,yy,zz, shading='gouraud') # fast colormesh function\r\nax.colormesh(xx,yy,zz, norm=norm) # slower colormesh function\r\nax.contour(xx,yy,zz, cmap='jet') # contour line plot\r\nax.contourf(xx,yy,zz, vmin=2, vmax=4) # filled contours plot\r\nn, bins, patch = ax.hist(x, 50) # histogram\r\nax.imshow(matrix, origin='lower', extent=(x1, x2, y1, y2)) # show image\r\nax.specgram(y, FS=0.1, noverlap=128, scale='linear') # plot a spectrogram\r\n```", + "note": "Don't delete this file! It's used internally to help with page regeneration." +} \ No newline at end of file diff --git a/stylesheets/github-light.css b/stylesheets/github-light.css new file mode 100644 index 0000000..d64ba5d --- /dev/null +++ b/stylesheets/github-light.css @@ -0,0 +1,124 @@ +/* +The MIT License (MIT) + +Copyright (c) 2015 GitHub, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +*/ + +.pl-c /* comment */ { + color: #969896; +} + +.pl-c1 /* constant, markup.raw, meta.diff.header, meta.module-reference, meta.property-name, support, support.constant, support.variable, variable.other.constant */, +.pl-s .pl-v /* string variable */ { + color: #0086b3; +} + +.pl-e /* entity */, +.pl-en /* entity.name */ { + color: #795da3; +} + +.pl-s .pl-s1 /* string source */, +.pl-smi /* storage.modifier.import, storage.modifier.package, storage.type.java, variable.other, variable.parameter.function */ { + color: #333; +} + +.pl-ent /* entity.name.tag */ { + color: #63a35c; +} + +.pl-k /* keyword, storage, storage.type */ { + color: #a71d5d; +} + +.pl-pds /* punctuation.definition.string, string.regexp.character-class */, +.pl-s /* string */, +.pl-s .pl-pse .pl-s1 /* string punctuation.section.embedded source */, +.pl-sr /* string.regexp */, +.pl-sr .pl-cce /* string.regexp constant.character.escape */, +.pl-sr .pl-sra /* string.regexp string.regexp.arbitrary-repitition */, +.pl-sr .pl-sre /* string.regexp source.ruby.embedded */ { + color: #183691; +} + +.pl-v /* variable */ { + color: #ed6a43; +} + +.pl-id /* invalid.deprecated */ { + color: #b52a1d; +} + +.pl-ii /* invalid.illegal */ { + background-color: #b52a1d; + color: #f8f8f8; +} + +.pl-sr .pl-cce /* string.regexp constant.character.escape */ { + color: #63a35c; + font-weight: bold; +} + +.pl-ml /* markup.list */ { + color: #693a17; +} + +.pl-mh /* markup.heading */, +.pl-mh .pl-en /* markup.heading entity.name */, +.pl-ms /* meta.separator */ { + color: #1d3e81; + font-weight: bold; +} + +.pl-mq /* markup.quote */ { + color: #008080; +} + +.pl-mi /* markup.italic */ { + color: #333; + font-style: italic; +} + +.pl-mb /* markup.bold */ { + color: #333; + font-weight: bold; +} + +.pl-md /* markup.deleted, meta.diff.header.from-file */ { + background-color: #ffecec; + color: #bd2c00; +} + +.pl-mi1 /* markup.inserted, meta.diff.header.to-file */ { + background-color: #eaffea; + color: #55a532; +} + +.pl-mdr /* meta.diff.range */ { + color: #795da3; + font-weight: bold; +} + +.pl-mo /* meta.output */ { + color: #1d3e81; +} + diff --git a/stylesheets/normalize.css b/stylesheets/normalize.css new file mode 100644 index 0000000..30366a6 --- /dev/null +++ b/stylesheets/normalize.css @@ -0,0 +1,424 @@ +/*! normalize.css v3.0.2 | MIT License | git.io/normalize */ + +/** + * 1. Set default font family to sans-serif. + * 2. Prevent iOS text size adjust after orientation change, without disabling + * user zoom. + */ + +html { + font-family: sans-serif; /* 1 */ + -ms-text-size-adjust: 100%; /* 2 */ + -webkit-text-size-adjust: 100%; /* 2 */ +} + +/** + * Remove default margin. + */ + +body { + margin: 0; +} + +/* HTML5 display definitions + ========================================================================== */ + +/** + * Correct `block` display not defined for any HTML5 element in IE 8/9. + * Correct `block` display not defined for `details` or `summary` in IE 10/11 + * and Firefox. + * Correct `block` display not defined for `main` in IE 11. + */ + +article, +aside, +details, +figcaption, +figure, +footer, +header, +hgroup, +main, +menu, +nav, +section, +summary { + display: block; +} + +/** + * 1. Correct `inline-block` display not defined in IE 8/9. + * 2. Normalize vertical alignment of `progress` in Chrome, Firefox, and Opera. + */ + +audio, +canvas, +progress, +video { + display: inline-block; /* 1 */ + vertical-align: baseline; /* 2 */ +} + +/** + * Prevent modern browsers from displaying `audio` without controls. + * Remove excess height in iOS 5 devices. + */ + +audio:not([controls]) { + display: none; + height: 0; +} + +/** + * Address `[hidden]` styling not present in IE 8/9/10. + * Hide the `template` element in IE 8/9/11, Safari, and Firefox < 22. + */ + +[hidden], +template { + display: none; +} + +/* Links + ========================================================================== */ + +/** + * Remove the gray background color from active links in IE 10. + */ + +a { + background-color: transparent; +} + +/** + * Improve readability when focused and also mouse hovered in all browsers. + */ + +a:active, +a:hover { + outline: 0; +} + +/* Text-level semantics + ========================================================================== */ + +/** + * Address styling not present in IE 8/9/10/11, Safari, and Chrome. + */ + +abbr[title] { + border-bottom: 1px dotted; +} + +/** + * Address style set to `bolder` in Firefox 4+, Safari, and Chrome. + */ + +b, +strong { + font-weight: bold; +} + +/** + * Address styling not present in Safari and Chrome. + */ + +dfn { + font-style: italic; +} + +/** + * Address variable `h1` font-size and margin within `section` and `article` + * contexts in Firefox 4+, Safari, and Chrome. + */ + +h1 { + font-size: 2em; + margin: 0.67em 0; +} + +/** + * Address styling not present in IE 8/9. + */ + +mark { + background: #ff0; + color: #000; +} + +/** + * Address inconsistent and variable font size in all browsers. + */ + +small { + font-size: 80%; +} + +/** + * Prevent `sub` and `sup` affecting `line-height` in all browsers. + */ + +sub, +sup { + font-size: 75%; + line-height: 0; + position: relative; + vertical-align: baseline; +} + +sup { + top: -0.5em; +} + +sub { + bottom: -0.25em; +} + +/* Embedded content + ========================================================================== */ + +/** + * Remove border when inside `a` element in IE 8/9/10. + */ + +img { + border: 0; +} + +/** + * Correct overflow not hidden in IE 9/10/11. + */ + +svg:not(:root) { + overflow: hidden; +} + +/* Grouping content + ========================================================================== */ + +/** + * Address margin not present in IE 8/9 and Safari. + */ + +figure { + margin: 1em 40px; +} + +/** + * Address differences between Firefox and other browsers. + */ + +hr { + box-sizing: content-box; + height: 0; +} + +/** + * Contain overflow in all browsers. + */ + +pre { + overflow: auto; +} + +/** + * Address odd `em`-unit font size rendering in all browsers. + */ + +code, +kbd, +pre, +samp { + font-family: monospace, monospace; + font-size: 1em; +} + +/* Forms + ========================================================================== */ + +/** + * Known limitation: by default, Chrome and Safari on OS X allow very limited + * styling of `select`, unless a `border` property is set. + */ + +/** + * 1. Correct color not being inherited. + * Known issue: affects color of disabled elements. + * 2. Correct font properties not being inherited. + * 3. Address margins set differently in Firefox 4+, Safari, and Chrome. + */ + +button, +input, +optgroup, +select, +textarea { + color: inherit; /* 1 */ + font: inherit; /* 2 */ + margin: 0; /* 3 */ +} + +/** + * Address `overflow` set to `hidden` in IE 8/9/10/11. + */ + +button { + overflow: visible; +} + +/** + * Address inconsistent `text-transform` inheritance for `button` and `select`. + * All other form control elements do not inherit `text-transform` values. + * Correct `button` style inheritance in Firefox, IE 8/9/10/11, and Opera. + * Correct `select` style inheritance in Firefox. + */ + +button, +select { + text-transform: none; +} + +/** + * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio` + * and `video` controls. + * 2. Correct inability to style clickable `input` types in iOS. + * 3. Improve usability and consistency of cursor style between image-type + * `input` and others. + */ + +button, +html input[type="button"], /* 1 */ +input[type="reset"], +input[type="submit"] { + -webkit-appearance: button; /* 2 */ + cursor: pointer; /* 3 */ +} + +/** + * Re-set default cursor for disabled elements. + */ + +button[disabled], +html input[disabled] { + cursor: default; +} + +/** + * Remove inner padding and border in Firefox 4+. + */ + +button::-moz-focus-inner, +input::-moz-focus-inner { + border: 0; + padding: 0; +} + +/** + * Address Firefox 4+ setting `line-height` on `input` using `!important` in + * the UA stylesheet. + */ + +input { + line-height: normal; +} + +/** + * It's recommended that you don't attempt to style these elements. + * Firefox's implementation doesn't respect box-sizing, padding, or width. + * + * 1. Address box sizing set to `content-box` in IE 8/9/10. + * 2. Remove excess padding in IE 8/9/10. + */ + +input[type="checkbox"], +input[type="radio"] { + box-sizing: border-box; /* 1 */ + padding: 0; /* 2 */ +} + +/** + * Fix the cursor style for Chrome's increment/decrement buttons. For certain + * `font-size` values of the `input`, it causes the cursor style of the + * decrement button to change from `default` to `text`. + */ + +input[type="number"]::-webkit-inner-spin-button, +input[type="number"]::-webkit-outer-spin-button { + height: auto; +} + +/** + * 1. Address `appearance` set to `searchfield` in Safari and Chrome. + * 2. Address `box-sizing` set to `border-box` in Safari and Chrome + * (include `-moz` to future-proof). + */ + +input[type="search"] { + -webkit-appearance: textfield; /* 1 */ /* 2 */ + box-sizing: content-box; +} + +/** + * Remove inner padding and search cancel button in Safari and Chrome on OS X. + * Safari (but not Chrome) clips the cancel button when the search input has + * padding (and `textfield` appearance). + */ + +input[type="search"]::-webkit-search-cancel-button, +input[type="search"]::-webkit-search-decoration { + -webkit-appearance: none; +} + +/** + * Define consistent border, margin, and padding. + */ + +fieldset { + border: 1px solid #c0c0c0; + margin: 0 2px; + padding: 0.35em 0.625em 0.75em; +} + +/** + * 1. Correct `color` not being inherited in IE 8/9/10/11. + * 2. Remove padding so people aren't caught out if they zero out fieldsets. + */ + +legend { + border: 0; /* 1 */ + padding: 0; /* 2 */ +} + +/** + * Remove default vertical scrollbar in IE 8/9/10/11. + */ + +textarea { + overflow: auto; +} + +/** + * Don't inherit the `font-weight` (applied by a rule above). + * NOTE: the default cannot safely be changed in Chrome and Safari on OS X. + */ + +optgroup { + font-weight: bold; +} + +/* Tables + ========================================================================== */ + +/** + * Remove most spacing between table cells. + */ + +table { + border-collapse: collapse; + border-spacing: 0; +} + +td, +th { + padding: 0; +} diff --git a/stylesheets/stylesheet.css b/stylesheets/stylesheet.css new file mode 100644 index 0000000..b5f20c2 --- /dev/null +++ b/stylesheets/stylesheet.css @@ -0,0 +1,245 @@ +* { + box-sizing: border-box; } + +body { + padding: 0; + margin: 0; + font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 16px; + line-height: 1.5; + color: #606c71; } + +a { + color: #1e6bb8; + text-decoration: none; } + a:hover { + text-decoration: underline; } + +.btn { + display: inline-block; + margin-bottom: 1rem; + color: rgba(255, 255, 255, 0.7); + background-color: rgba(255, 255, 255, 0.08); + border-color: rgba(255, 255, 255, 0.2); + border-style: solid; + border-width: 1px; + border-radius: 0.3rem; + transition: color 0.2s, background-color 0.2s, border-color 0.2s; } + .btn + .btn { + margin-left: 1rem; } + +.btn:hover { + color: rgba(255, 255, 255, 0.8); + text-decoration: none; + background-color: rgba(255, 255, 255, 0.2); + border-color: rgba(255, 255, 255, 0.3); } + +@media screen and (min-width: 64em) { + .btn { + padding: 0.75rem 1rem; } } + +@media screen and (min-width: 42em) and (max-width: 64em) { + .btn { + padding: 0.6rem 0.9rem; + font-size: 0.9rem; } } + +@media screen and (max-width: 42em) { + .btn { + display: block; + width: 100%; + padding: 0.75rem; + font-size: 0.9rem; } + .btn + .btn { + margin-top: 1rem; + margin-left: 0; } } + +.page-header { + color: #fff; + text-align: center; + background-color: #159957; + background-image: linear-gradient(120deg, #155799, #159957); } + +@media screen and (min-width: 64em) { + .page-header { + padding: 5rem 6rem; } } + +@media screen and (min-width: 42em) and (max-width: 64em) { + .page-header { + padding: 3rem 4rem; } } + +@media screen and (max-width: 42em) { + .page-header { + padding: 2rem 1rem; } } + +.project-name { + margin-top: 0; + margin-bottom: 0.1rem; } + +@media screen and (min-width: 64em) { + .project-name { + font-size: 3.25rem; } } + +@media screen and (min-width: 42em) and (max-width: 64em) { + .project-name { + font-size: 2.25rem; } } + +@media screen and (max-width: 42em) { + .project-name { + font-size: 1.75rem; } } + +.project-tagline { + margin-bottom: 2rem; + font-weight: normal; + opacity: 0.7; } + +@media screen and (min-width: 64em) { + .project-tagline { + font-size: 1.25rem; } } + +@media screen and (min-width: 42em) and (max-width: 64em) { + .project-tagline { + font-size: 1.15rem; } } + +@media screen and (max-width: 42em) { + .project-tagline { + font-size: 1rem; } } + +.main-content :first-child { + margin-top: 0; } +.main-content img { + max-width: 100%; } +.main-content h1, .main-content h2, .main-content h3, .main-content h4, .main-content h5, .main-content h6 { + margin-top: 2rem; + margin-bottom: 1rem; + font-weight: normal; + color: #159957; } +.main-content p { + margin-bottom: 1em; } +.main-content code { + padding: 2px 4px; + font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace; + font-size: 0.9rem; + color: #383e41; + background-color: #f3f6fa; + border-radius: 0.3rem; } +.main-content pre { + padding: 0.8rem; + margin-top: 0; + margin-bottom: 1rem; + font: 1rem Consolas, "Liberation Mono", Menlo, Courier, monospace; + color: #567482; + word-wrap: normal; + background-color: #f3f6fa; + border: solid 1px #dce6f0; + border-radius: 0.3rem; } + .main-content pre > code { + padding: 0; + margin: 0; + font-size: 0.9rem; + color: #567482; + word-break: normal; + white-space: pre; + background: transparent; + border: 0; } +.main-content .highlight { + margin-bottom: 1rem; } + .main-content .highlight pre { + margin-bottom: 0; + word-break: normal; } +.main-content .highlight pre, .main-content pre { + padding: 0.8rem; + overflow: auto; + font-size: 0.9rem; + line-height: 1.45; + border-radius: 0.3rem; } +.main-content pre code, .main-content pre tt { + display: inline; + max-width: initial; + padding: 0; + margin: 0; + overflow: initial; + line-height: inherit; + word-wrap: normal; + background-color: transparent; + border: 0; } + .main-content pre code:before, .main-content pre code:after, .main-content pre tt:before, .main-content pre tt:after { + content: normal; } +.main-content ul, .main-content ol { + margin-top: 0; } +.main-content blockquote { + padding: 0 1rem; + margin-left: 0; + color: #819198; + border-left: 0.3rem solid #dce6f0; } + .main-content blockquote > :first-child { + margin-top: 0; } + .main-content blockquote > :last-child { + margin-bottom: 0; } +.main-content table { + display: block; + width: 100%; + overflow: auto; + word-break: normal; + word-break: keep-all; } + .main-content table th { + font-weight: bold; } + .main-content table th, .main-content table td { + padding: 0.5rem 1rem; + border: 1px solid #e9ebec; } +.main-content dl { + padding: 0; } + .main-content dl dt { + padding: 0; + margin-top: 1rem; + font-size: 1rem; + font-weight: bold; } + .main-content dl dd { + padding: 0; + margin-bottom: 1rem; } +.main-content hr { + height: 2px; + padding: 0; + margin: 1rem 0; + background-color: #eff0f1; + border: 0; } + +@media screen and (min-width: 64em) { + .main-content { + max-width: 64rem; + padding: 2rem 6rem; + margin: 0 auto; + font-size: 1.1rem; } } + +@media screen and (min-width: 42em) and (max-width: 64em) { + .main-content { + padding: 2rem 4rem; + font-size: 1.1rem; } } + +@media screen and (max-width: 42em) { + .main-content { + padding: 2rem 1rem; + font-size: 1rem; } } + +.site-footer { + padding-top: 2rem; + margin-top: 2rem; + border-top: solid 1px #eff0f1; } + +.site-footer-owner { + display: block; + font-weight: bold; } + +.site-footer-credits { + color: #819198; } + +@media screen and (min-width: 64em) { + .site-footer { + font-size: 1rem; } } + +@media screen and (min-width: 42em) and (max-width: 64em) { + .site-footer { + font-size: 1rem; } } + +@media screen and (max-width: 42em) { + .site-footer { + font-size: 0.9rem; } } From ce539c91d11bc6339049e025a60577cc95a66d99 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Fri, 22 Apr 2016 11:53:09 +0200 Subject: [PATCH 02/96] try 2 columns solution --- stylesheets/stylesheet.css | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/stylesheets/stylesheet.css b/stylesheets/stylesheet.css index b5f20c2..0df7b1d 100644 --- a/stylesheets/stylesheet.css +++ b/stylesheets/stylesheet.css @@ -104,6 +104,10 @@ a { .project-tagline { font-size: 1rem; } } +.main-content { + column-count:2; + -moz-column-count:2; + -webkit-column-count: 2;} .main-content :first-child { margin-top: 0; } .main-content img { From 4db01282e65c255ff0bbb5644afcb5978bc96454 Mon Sep 17 00:00:00 2001 From: MMesch Date: Fri, 22 Apr 2016 12:03:03 +0200 Subject: [PATCH 03/96] test 3 columns --- stylesheets/stylesheet.css | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/stylesheets/stylesheet.css b/stylesheets/stylesheet.css index 0df7b1d..6520297 100644 --- a/stylesheets/stylesheet.css +++ b/stylesheets/stylesheet.css @@ -105,9 +105,9 @@ a { font-size: 1rem; } } .main-content { - column-count:2; - -moz-column-count:2; - -webkit-column-count: 2;} + column-count:3; + -moz-column-count:3; + -webkit-column-count: 3;} .main-content :first-child { margin-top: 0; } .main-content img { From ce6f1e5346559404d6a7b8603550ee5feafc0553 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Fri, 22 Apr 2016 12:05:31 +0200 Subject: [PATCH 04/96] trying to expand sheet over width of screen. --- stylesheets/stylesheet.css | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/stylesheets/stylesheet.css b/stylesheets/stylesheet.css index 6520297..cff6bee 100644 --- a/stylesheets/stylesheet.css +++ b/stylesheets/stylesheet.css @@ -107,7 +107,9 @@ a { .main-content { column-count:3; -moz-column-count:3; - -webkit-column-count: 3;} + -webkit-column-count: 3; + box-sizing: unset; +} .main-content :first-child { margin-top: 0; } .main-content img { From 81c2ffda68f1e4d23ad905ef210926700b076e96 Mon Sep 17 00:00:00 2001 From: MMesch Date: Fri, 22 Apr 2016 12:12:32 +0200 Subject: [PATCH 05/96] automatic columns --- stylesheets/stylesheet.css | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/stylesheets/stylesheet.css b/stylesheets/stylesheet.css index cff6bee..daefc6f 100644 --- a/stylesheets/stylesheet.css +++ b/stylesheets/stylesheet.css @@ -105,9 +105,10 @@ a { font-size: 1rem; } } .main-content { - column-count:3; - -moz-column-count:3; - -webkit-column-count: 3; + column-count:auto; + -moz-column-count:auto; + -webkit-column-count: auto; + column-width=300; box-sizing: unset; } .main-content :first-child { From 0db79d91c483cb51b90e87ead4ed45703800da95 Mon Sep 17 00:00:00 2001 From: MMesch Date: Fri, 22 Apr 2016 12:15:00 +0200 Subject: [PATCH 06/96] another try --- stylesheets/stylesheet.css | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/stylesheets/stylesheet.css b/stylesheets/stylesheet.css index daefc6f..4d6866c 100644 --- a/stylesheets/stylesheet.css +++ b/stylesheets/stylesheet.css @@ -108,7 +108,11 @@ a { column-count:auto; -moz-column-count:auto; -webkit-column-count: auto; - column-width=300; + + -webkit-column-width: 100px; + -moz-column-width: 100px; + column-width: 100px; + box-sizing: unset; } .main-content :first-child { From 20bf642902e7f6de0d2f15c2c3d54e35a422cc6b Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Fri, 22 Apr 2016 12:59:25 +0200 Subject: [PATCH 07/96] Update index.html --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index cea306a..07265ff 100644 --- a/index.html +++ b/index.html @@ -3,7 +3,7 @@ Scientific python cheat sheet by IPGP - + From 1e78b123e2a4fc8490b345ed5831cc40a991ba85 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Fri, 22 Apr 2016 13:00:33 +0200 Subject: [PATCH 08/96] Update stylesheet.css --- stylesheets/stylesheet.css | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/stylesheets/stylesheet.css b/stylesheets/stylesheet.css index 4d6866c..9ac6fd1 100644 --- a/stylesheets/stylesheet.css +++ b/stylesheets/stylesheet.css @@ -105,16 +105,10 @@ a { font-size: 1rem; } } .main-content { + box-sizing: unset; column-count:auto; -moz-column-count:auto; - -webkit-column-count: auto; - - -webkit-column-width: 100px; - -moz-column-width: 100px; - column-width: 100px; - - box-sizing: unset; -} + -webkit-column-count: auto;} .main-content :first-child { margin-top: 0; } .main-content img { From 3cca722273024e29f03637b2071a5b3d6da30aed Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Fri, 22 Apr 2016 13:01:13 +0200 Subject: [PATCH 09/96] Update stylesheet.css --- stylesheets/stylesheet.css | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/stylesheets/stylesheet.css b/stylesheets/stylesheet.css index 9ac6fd1..a0790b6 100644 --- a/stylesheets/stylesheet.css +++ b/stylesheets/stylesheet.css @@ -106,9 +106,9 @@ a { .main-content { box-sizing: unset; - column-count:auto; - -moz-column-count:auto; - -webkit-column-count: auto;} + column-count:3; + -moz-column-count:3; + -webkit-column-count: 3;} .main-content :first-child { margin-top: 0; } .main-content img { From 7f18bd9b0a0ebe942004d935f5adee717b4af3b0 Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 22 Apr 2016 13:08:31 +0200 Subject: [PATCH 10/96] better layout --- stylesheets/stylesheet.css | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/stylesheets/stylesheet.css b/stylesheets/stylesheet.css index 4d6866c..a83c891 100644 --- a/stylesheets/stylesheet.css +++ b/stylesheets/stylesheet.css @@ -109,9 +109,9 @@ a { -moz-column-count:auto; -webkit-column-count: auto; - -webkit-column-width: 100px; - -moz-column-width: 100px; - column-width: 100px; + -webkit-column-width: 200px; + -moz-column-width: 200px; + column-width: 200px; box-sizing: unset; } @@ -216,7 +216,7 @@ a { @media screen and (min-width: 64em) { .main-content { - max-width: 64rem; + /*max-width: 64rem;*/ padding: 2rem 6rem; margin: 0 auto; font-size: 1.1rem; } } From 0390763860bbca330277194000ea750ae358673c Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 22 Apr 2016 13:11:23 +0200 Subject: [PATCH 11/96] broader columns --- stylesheets/stylesheet.css | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/stylesheets/stylesheet.css b/stylesheets/stylesheet.css index 3a3ac8e..5367468 100644 --- a/stylesheets/stylesheet.css +++ b/stylesheets/stylesheet.css @@ -109,9 +109,9 @@ a { -moz-column-count:auto; -webkit-column-count: auto; - -webkit-column-width: 200px; - -moz-column-width: 200px; - column-width: 200px; + -webkit-column-width: 330px; + -moz-column-width: 330px; + column-width: 330px; box-sizing: unset;} .main-content :first-child { From 123a86f8ed258d76595f458ac2dcba069b0ac313 Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 22 Apr 2016 13:12:43 +0200 Subject: [PATCH 12/96] removed header --- index.html | 8 -------- 1 file changed, 8 deletions(-) diff --git a/index.html b/index.html index 07265ff..02f8fc6 100644 --- a/index.html +++ b/index.html @@ -10,14 +10,6 @@ - -

Scientific Python Cheatsheet

From a7bc6d058966170f3c01e2be16027bade4e86163 Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 22 Apr 2016 13:21:38 +0200 Subject: [PATCH 13/96] smaller fonts --- index.html | 2 +- stylesheets/stylesheet.css | 20 ++++++++++---------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/index.html b/index.html index 02f8fc6..21e3748 100644 --- a/index.html +++ b/index.html @@ -19,7 +19,7 @@

Table of Contents

    -
  • +
  • Scientific Python Cheatsheet
      diff --git a/stylesheets/stylesheet.css b/stylesheets/stylesheet.css index 5367468..1c7aadf 100644 --- a/stylesheets/stylesheet.css +++ b/stylesheets/stylesheet.css @@ -128,7 +128,7 @@ a { .main-content code { padding: 2px 4px; font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace; - font-size: 0.9rem; + font-size: 0.7rem; color: #383e41; background-color: #f3f6fa; border-radius: 0.3rem; } @@ -145,7 +145,7 @@ a { .main-content pre > code { padding: 0; margin: 0; - font-size: 0.9rem; + font-size: 0.7rem; color: #567482; word-break: normal; white-space: pre; @@ -159,7 +159,7 @@ a { .main-content .highlight pre, .main-content pre { padding: 0.8rem; overflow: auto; - font-size: 0.9rem; + font-size: 0.7rem; line-height: 1.45; border-radius: 0.3rem; } .main-content pre code, .main-content pre tt { @@ -201,7 +201,7 @@ a { .main-content dl dt { padding: 0; margin-top: 1rem; - font-size: 1rem; + font-size: 0.8rem; font-weight: bold; } .main-content dl dd { padding: 0; @@ -218,17 +218,17 @@ a { /*max-width: 64rem;*/ padding: 2rem 6rem; margin: 0 auto; - font-size: 1.1rem; } } + font-size: 1.0rem; } } @media screen and (min-width: 42em) and (max-width: 64em) { .main-content { padding: 2rem 4rem; - font-size: 1.1rem; } } + font-size: 1.0rem; } } @media screen and (max-width: 42em) { .main-content { padding: 2rem 1rem; - font-size: 1rem; } } + font-size: 0.9rem; } } .site-footer { padding-top: 2rem; @@ -244,12 +244,12 @@ a { @media screen and (min-width: 64em) { .site-footer { - font-size: 1rem; } } + font-size: 0.9rem; } } @media screen and (min-width: 42em) and (max-width: 64em) { .site-footer { - font-size: 1rem; } } + font-size: 0.9rem; } } @media screen and (max-width: 42em) { .site-footer { - font-size: 0.9rem; } } + font-size: 0.7rem; } } From 006d176818efa5035d688da2a8e8c00dd79c5466 Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 22 Apr 2016 13:38:40 +0200 Subject: [PATCH 14/96] grouped columns --- index.html | 8 ++++++-- stylesheets/stylesheet.css | 11 ++++++++++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/index.html b/index.html index 21e3748..fcf3a61 100644 --- a/index.html +++ b/index.html @@ -14,8 +14,6 @@

      Scientific Python Cheatsheet

      - -

      Table of Contents

        @@ -87,6 +85,7 @@

        +

        Pure Python

        @@ -251,7 +250,9 @@

        print 'func' my_func()

        + +

        NumPy

        @@ -373,7 +374,9 @@

        np.random.rand(200) # 200 random numbers in [0, 1) np.random.uniform(1, 30, 200) # 200 random numbers in [1, 30) np.random.random_integers(1, 15, 300) # 300 random integers between [1, 15]

        + +

        Matplotlib

        @@ -416,6 +419,7 @@

        n, bins, patch = ax.hist(x, 50) # histogram ax.imshow(matrix, origin='lower', extent=(x1, x2, y1, y2)) # show image ax.specgram(y, FS=0.1, noverlap=128, scale='linear') # plot a spectrogram

        +
        Scientific python cheat sheet is maintained by IPGP. diff --git a/stylesheets/stylesheet.css b/stylesheets/stylesheet.css index 1c7aadf..8e658a8 100644 --- a/stylesheets/stylesheet.css +++ b/stylesheets/stylesheet.css @@ -114,11 +114,20 @@ a { column-width: 330px; box-sizing: unset;} + +div.group { + display: inline-block; + width: 100%;} .main-content :first-child { margin-top: 0; } .main-content img { max-width: 100%; } -.main-content h1, .main-content h2, .main-content h3, .main-content h4, .main-content h5, .main-content h6 { +.main-content h1 { + margin-top: 2rem; + margin-bottom: 1rem; + font-weight: normal; + color: #159957; } +.main-content h2, .main-content h3, .main-content h4, .main-content h5, .main-content h6 { margin-top: 2rem; margin-bottom: 1rem; font-weight: normal; From d81a28d57e316e32a6bf7ff9dce1c2430fdb5148 Mon Sep 17 00:00:00 2001 From: Matthias Date: Fri, 22 Apr 2016 17:05:23 +0200 Subject: [PATCH 15/96] group class inside main-content --- stylesheets/stylesheet.css | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/stylesheets/stylesheet.css b/stylesheets/stylesheet.css index 8e658a8..134c774 100644 --- a/stylesheets/stylesheet.css +++ b/stylesheets/stylesheet.css @@ -115,25 +115,31 @@ a { box-sizing: unset;} -div.group { +.main-content .group { display: inline-block; width: 100%;} + .main-content :first-child { margin-top: 0; } + .main-content img { max-width: 100%; } + .main-content h1 { margin-top: 2rem; margin-bottom: 1rem; font-weight: normal; color: #159957; } + .main-content h2, .main-content h3, .main-content h4, .main-content h5, .main-content h6 { margin-top: 2rem; margin-bottom: 1rem; font-weight: normal; color: #159957; } + .main-content p { margin-bottom: 1em; } + .main-content code { padding: 2px 4px; font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace; @@ -141,6 +147,7 @@ div.group { color: #383e41; background-color: #f3f6fa; border-radius: 0.3rem; } + .main-content pre { padding: 0.8rem; margin-top: 0; @@ -160,17 +167,20 @@ div.group { white-space: pre; background: transparent; border: 0; } + .main-content .highlight { margin-bottom: 1rem; } .main-content .highlight pre { margin-bottom: 0; word-break: normal; } + .main-content .highlight pre, .main-content pre { padding: 0.8rem; overflow: auto; font-size: 0.7rem; line-height: 1.45; border-radius: 0.3rem; } + .main-content pre code, .main-content pre tt { display: inline; max-width: initial; @@ -183,8 +193,10 @@ div.group { border: 0; } .main-content pre code:before, .main-content pre code:after, .main-content pre tt:before, .main-content pre tt:after { content: normal; } + .main-content ul, .main-content ol { margin-top: 0; } + .main-content blockquote { padding: 0 1rem; margin-left: 0; @@ -194,6 +206,7 @@ div.group { margin-top: 0; } .main-content blockquote > :last-child { margin-bottom: 0; } + .main-content table { display: block; width: 100%; @@ -205,6 +218,7 @@ div.group { .main-content table th, .main-content table td { padding: 0.5rem 1rem; border: 1px solid #e9ebec; } + .main-content dl { padding: 0; } .main-content dl dt { @@ -215,6 +229,7 @@ div.group { .main-content dl dd { padding: 0; margin-bottom: 1rem; } + .main-content hr { height: 2px; padding: 0; From 8c020b7d7f7496f41bad64eb19da5590a78fd2cd Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 25 Apr 2016 15:24:38 +0200 Subject: [PATCH 16/96] regenerad website revision: dbf0dff --- index.html | 674 +++++++++++++++++++++++------------------------------ 1 file changed, 295 insertions(+), 379 deletions(-) diff --git a/index.html b/index.html index fcf3a61..2297c48 100644 --- a/index.html +++ b/index.html @@ -1,3 +1,4 @@ + @@ -8,54 +9,64 @@ + +
        -

        -Scientific Python Cheatsheet

        -

        Table of Contents

        +

        Scientific Python Cheatsheet

        +

        Table of Contents

        +
      • Matplotlib
      • +

    -
  • -
- - - - - -
-

-Pure Python

- -

-Types

- -
a = 2           # integer
-b = 5.0         # float
-c = 8.3e5       # exponential
-d = 1.5 + 0.5j  # complex
-e = 3 > 4       # boolean
-f = 'word'      # string
- -

-Lists

- -
a = ['red', 'blue', 'green']      # manually initialization
-b = range(5)                      # initialization through a function
-c = [nu**2 for nu in b]           # initialize through list comprehension
-d = [nu**2 for nu in b if b < 3]  # list comprehension withcondition
-e = c[0]                          # access element
-f = e[1: 2]                       # access a slice of the list
-g = ['re', 'bl'] + ['gr']         # list concatenation
-h = ['re'] * 5                    # repeat a list
-['re', 'bl'].index('re')          # returns index of 're'
-'re' in ['re', 'bl']              # true if 're' in list
-sorted([3, 2, 1])                 # returns sorted list
-z = ['red'] + ['green', 'blue']   # list concatenation
- -

-Dictionaries

- -
a = {'red': 'rouge', 'blue': 'bleu', 'green': 'vert'}  # dictionary
-b = a['red']                                           # translate item
-c = [value for key, value in b.items()]                # loop through contents
-d = a.get('yellow', 'no translation found')            # return default
- -

-Strings

- -
a = 'red'                      # assignment
-char = a[2]                    # access individual characters
-'red ' + 'blue'                # string concatenation
-'1, 2, three'.split(',')       # split string into list
-'.'.join(['1', '2', 'three'])  # concatenate list into string
- -

-Operators

- -
a = 2             # assignment
-a += 1 (*=, /=)   # change and assign
-3 + 2             # addition
-3 / 2             # integer division (python2) or float division (python3)
-3 // 2            # integer division
-3 * 2             # multiplication
-3 ** 2            # exponent
-3 % 2             # remainder
-abs()             # absolute value
-1 == 1            # equal
-2 > 1             # larger
-2 < 1             # smaller
-1 != 2            # not equal
-1 != 2 and 2 < 3  # logical AND
-1 != 2 or 2 < 3   # logical OR
-not 1 == 2        # logical NOT
-a in b            # test if a is in b
-a is b            # test if objects point to the same memory (id)
- -

-Control Flow

- -

-if/elif/else

- -
a, b = 1, 2
-if a + b == 3:
-    print 'True'
-elif a + b == 1:
-    print 'False'
-else:
-    print '?'
- -

-for

- -
a = ['red', 'blue',
-     'green']
-for color in a:
-    print color
- -

-while

- -
number = 1
-while number < 10:
-    print number
-    number += 1
- -

-break

- -
number = 1
-while True:
-    print number
-    number += 1
-    if number > 10:
-        break
- -

-continue

- -
for i in range(20):
-    if i % 2 == 0:
-        continue
-    print i
- -

-Functions, Classes, Generators, Decorators

- -

-Function

- -
def myfunc(a1, a2):
-    return x
-
-x = my_function(a1,a2)
- -

-Class

- -
class Point(object):
-    def __init__(self, x):
-        self.x = x
-    def __call__(self):
-        print self.x
-
-x = Point(3)
- -

-Generators

- -
def firstn(n):
-    num = 0
-    while num < n:
-        yield num
-        num += 1
-
-x = [for i in firstn(10)]
- -

-Decorators

- -
class myDecorator(object):
-    def __init__(self, f):
-        self.f = f
-    def __call__(self):
-        print "call"
-        self.f()
-
-@myDecorator
-def my_funct():
-    print 'func'
-
-my_func()
+
+

Pure Python

+

Types

+
a = 2           # integer
+b = 5.0         # float
+c = 8.3e5       # exponential
+d = 1.5 + 0.5j  # complex
+e = 3 > 4       # boolean
+f = 'word'      # string
+

Lists

+
a = ['red', 'blue', 'green']      # manually initialization
+b = range(5)                      # initialization through a function
+c = [nu**2 for nu in b]           # initialize through list comprehension
+d = [nu**2 for nu in b if b < 3]  # list comprehension withcondition
+e = c[0]                          # access element
+f = e[1: 2]                       # access a slice of the list
+g = ['re', 'bl'] + ['gr']         # list concatenation
+h = ['re'] * 5                    # repeat a list
+['re', 'bl'].index('re')          # returns index of 're'
+'re' in ['re', 'bl']              # true if 're' in list
+sorted([3, 2, 1])                 # returns sorted list
+z = ['red'] + ['green', 'blue']   # list concatenation
+

Dictionaries

+
a = {'red': 'rouge', 'blue': 'bleu', 'green': 'vert'}  # dictionary
+b = a['red']                                           # translate item
+c = [value for key, value in b.items()]                # loop through contents
+d = a.get('yellow', 'no translation found')            # return default
+

Strings

+
a = 'red'                      # assignment
+char = a[2]                    # access individual characters
+'red ' + 'blue'                # string concatenation
+'1, 2, three'.split(',')       # split string into list
+'.'.join(['1', '2', 'three'])  # concatenate list into string
+

Operators

+
a = 2             # assignment
+a += 1 (*=, /=)   # change and assign
+3 + 2             # addition
+3 / 2             # integer division (python2) or float division (python3)
+3 // 2            # integer division
+3 * 2             # multiplication
+3 ** 2            # exponent
+3 % 2             # remainder
+abs()             # absolute value
+1 == 1            # equal
+2 > 1             # larger
+2 < 1             # smaller
+1 != 2            # not equal
+1 != 2 and 2 < 3  # logical AND
+1 != 2 or 2 < 3   # logical OR
+not 1 == 2        # logical NOT
+a in b            # test if a is in b
+a is b            # test if objects point to the same memory (id)
+

Control Flow

+
# if/elif/else
+a, b = 1, 2
+if a + b == 3:
+    print 'True'
+elif a + b == 1:
+    print 'False'
+else:
+    print '?'
+    
+# for
+a = ['red', 'blue', 'green']
+for color in a:
+    print color
+    
+# while
+number = 1
+while number < 10:
+    print number
+    number += 1
+
+# break
+number = 1
+while True:
+    print number
+    number += 1
+    if number > 10:
+        break
+
+# continue
+for i in range(20):
+    if i % 2 == 0:
+        continue
+    print i
+

Functions, Classes, Generators, Decorators

+
# Function
+def myfunc(a1, a2):
+    return x
+
+x = my_function(a1,a2)
+
+# Class
+class Point(object):
+    def __init__(self, x):
+        self.x = x
+    def __call__(self):
+        print self.x
+
+x = Point(3)
+
+# Generators
+def firstn(n):
+    num = 0
+    while num < n:
+        yield num
+        num += 1
+
+x = [for i in firstn(10)]
+
+# Decorators
+class myDecorator(object):
+    def __init__(self, f):
+        self.f = f
+    def __call__(self):
+        print "call"
+        self.f()
+
+@myDecorator
+def my_funct():
+    print 'func'
+
+my_func()
- -
-

-NumPy

- -

-array initialization

- -
np.array([2, 3, 4])             # direct initialization
-np.empty(20, dtype=np.float32)  # single precision array with 20 entries
-np.zeros(200)                   # initialize 200 zeros
-np.ones((3,3), dtype=np.int32)  # 3 x 3 integer matrix with ones
-np.eye(200)                     # ones on the diagonal
-np.zeros_like(a)                # returns array with zeros and the shape of a
-np.linspace(0., 10., 100)       # 100 points from 0 to 10
-np.arange(0, 100, 2)            # points from 0 to <100 with step width 2
-np.logspace(-5, 2, 100)         # 100 log-spaced points between 1e-5 and 1e2
-np.copy(a)                      # copy array to new memory
- -

-reading/ writing files

- -
np.fromfile(fname/object, dtype=np.float32, count=5)  # read binary data from file
-np.loadtxt(fname/object, skiprows=2, delimiter=',')   # read ascii data from file
- -

-array properties and operations

- -
a.shape                # a tuple with the lengths of each axis
-len(a)                 # length of axis 0
-a.ndim                 # number of dimensions (axes)
-a.sort(axis=1)         # sort array along axis
-a.flatten()            # collapse array to one dimension
-a.conj()               # return complex conjugate
-a.astype(np.int16)     # cast to integer
-np.argmax(a, axis=2)   # return index of maximum along a given axis
-np.cumsum(a)           # return cumulative sum
-np.any(a)              # True if any element is True
-np.all(a)              # True if all elements are True
-np.argsort(a, axis=1)  # return sorted index array along axis
- -

-indexing

- -
a = np.arange(100)          # initialization with 0 - 99
-a[: 3] = 0                  # set the first three indices to zero
-a[1: 5] = 1                 # set indices 1-4 to 1
-a[start:stop:step]          # general form of indexing/slicing
-a[None, :]                  # transform to column vector
-a[[1, 1, 3, 8]]             # return array with values of the indices
-a = a.reshape(10, 10)       # transform to 10 x 10 matrix
-a.T                         # return transposed view
-np.transpose(a, (2, 1, 0))  # transpose array to new axis order
-a[a < 2]                    # returns array that fulfills elementwise condition
- -

-boolean arrays

- -
a < 2                          # returns array with boolean values
-np.logical_and(a < 2, b > 10)  # elementwise logical and
-np.logical_or(a < 2, b > 10)   # elementwise logical or
-~a                             # invert boolean array
-np.invert(a)                   # invert boolean array
- -

-elementwise operations and math functions

- -
a * 5              # multiplication with scalar
-a + 5              # addition with scalar
-a + b              # addition with array b
-a / b              # division with b (np.NaN for division by zero)
-np.exp(a)          # exponential (complex and real)
-np.sin(a)          # sine
-np.cos(a)          # cosine
-np.arctan2(y,x)    # arctan(y/x)
-np.arcsin(x)       # arcsin
-np.radians(a)      # degrees to radians
-np.degrees(a)      # radians to degrees
-np.var(a)          # variance of array
-np.std(a, axis=1)  # standard deviation
- -

-inner / outer products

- -
np.dot(a, b)                        # inner matrix product: a_mi b_in
-np.einsum('ijkl,klmn->ijmn', a, b)  # einstein summation convention
-np.sum(a, axis=1)                   # sum over axis 1
-np.abs(a)                           # return array with absolute values
-a[None, :] + b[:, None]             # outer sum
-a[None, :] * b[None, :]             # outer product
-np.outer(a, b)                      # outer product
-np.sum(a * a.T)                     # matrix norm
- -

-interpolation, integration

- -
np.trapz(y, x=x, axis=1)  # integrate along axis 1
-np.interp(x, xp, yp)      # interpolate function xp, yp at points x
- -

-fft

- -
np.fft.fft(y)             # complex fourier transform of y
-np.fft.fftfreqs(len(y))   # fft frequencies for a given length
-np.fft.fftshift(freqs)    # shifts zero frequency to the middle
-np.fft.rfft(y)            # real fourier transform of y
-np.fft.rfftfreqs(len(y))  # real fft frequencies for a given length
- -

-rounding

- -
np.ceil(a)   # rounds to nearest upper int
-np.floor(a)  # rounds to nearest lower int
-np.round(a)  # rounds to neares int
- -

-random variables

- -
np.random.normal(loc=0, scale=2, size=100)  # 100 normal distributed random numbers
-np.random.seed(23032)                       # resets the seed value
-np.random.rand(200)                         # 200 random numbers in [0, 1)
-np.random.uniform(1, 30, 200)               # 200 random numbers in [1, 30)
-np.random.random_integers(1, 15, 300)       # 300 random integers between [1, 15]
+
+

NumPy

+

array initialization

+
np.array([2, 3, 4])             # direct initialization
+np.empty(20, dtype=np.float32)  # single precision array with 20 entries
+np.zeros(200)                   # initialize 200 zeros
+np.ones((3,3), dtype=np.int32)  # 3 x 3 integer matrix with ones
+np.eye(200)                     # ones on the diagonal
+np.zeros_like(a)                # returns array with zeros and the shape of a
+np.linspace(0., 10., 100)       # 100 points from 0 to 10
+np.arange(0, 100, 2)            # points from 0 to <100 with step width 2
+np.logspace(-5, 2, 100)         # 100 log-spaced points between 1e-5 and 1e2
+np.copy(a)                      # copy array to new memory
+

reading/ writing files

+
np.fromfile(fname/object, dtype=np.float32, count=5)  # read binary data from file
+np.loadtxt(fname/object, skiprows=2, delimiter=',')   # read ascii data from file
+

array properties and operations

+
a.shape                # a tuple with the lengths of each axis
+len(a)                 # length of axis 0
+a.ndim                 # number of dimensions (axes)
+a.sort(axis=1)         # sort array along axis
+a.flatten()            # collapse array to one dimension
+a.conj()               # return complex conjugate
+a.astype(np.int16)     # cast to integer
+np.argmax(a, axis=2)   # return index of maximum along a given axis
+np.cumsum(a)           # return cumulative sum
+np.any(a)              # True if any element is True
+np.all(a)              # True if all elements are True
+np.argsort(a, axis=1)  # return sorted index array along axis
+

indexing

+
a = np.arange(100)          # initialization with 0 - 99
+a[: 3] = 0                  # set the first three indices to zero
+a[1: 5] = 1                 # set indices 1-4 to 1
+a[start:stop:step]          # general form of indexing/slicing
+a[None, :]                  # transform to column vector
+a[[1, 1, 3, 8]]             # return array with values of the indices
+a = a.reshape(10, 10)       # transform to 10 x 10 matrix
+a.T                         # return transposed view
+np.transpose(a, (2, 1, 0))  # transpose array to new axis order
+a[a < 2]                    # returns array that fulfills elementwise condition
+

boolean arrays

+
a < 2                          # returns array with boolean values
+np.logical_and(a < 2, b > 10)  # elementwise logical and
+np.logical_or(a < 2, b > 10)   # elementwise logical or
+~a                             # invert boolean array
+np.invert(a)                   # invert boolean array
+

elementwise operations and math functions

+
a * 5              # multiplication with scalar
+a + 5              # addition with scalar
+a + b              # addition with array b
+a / b              # division with b (np.NaN for division by zero)
+np.exp(a)          # exponential (complex and real)
+np.sin(a)          # sine
+np.cos(a)          # cosine
+np.arctan2(y,x)    # arctan(y/x)
+np.arcsin(x)       # arcsin
+np.radians(a)      # degrees to radians
+np.degrees(a)      # radians to degrees
+np.var(a)          # variance of array
+np.std(a, axis=1)  # standard deviation
+

inner / outer products

+
np.dot(a, b)                        # inner matrix product: a_mi b_in
+np.einsum('ijkl,klmn->ijmn', a, b)  # einstein summation convention
+np.sum(a, axis=1)                   # sum over axis 1
+np.abs(a)                           # return array with absolute values
+a[None, :] + b[:, None]             # outer sum
+a[None, :] * b[None, :]             # outer product
+np.outer(a, b)                      # outer product
+np.sum(a * a.T)                     # matrix norm
+

interpolation, integration

+
np.trapz(y, x=x, axis=1)  # integrate along axis 1
+np.interp(x, xp, yp)      # interpolate function xp, yp at points x
+

fft

+
np.fft.fft(y)             # complex fourier transform of y
+np.fft.fftfreqs(len(y))   # fft frequencies for a given length
+np.fft.fftshift(freqs)    # shifts zero frequency to the middle
+np.fft.rfft(y)            # real fourier transform of y
+np.fft.rfftfreqs(len(y))  # real fft frequencies for a given length
+

rounding

+
np.ceil(a)   # rounds to nearest upper int
+np.floor(a)  # rounds to nearest lower int
+np.round(a)  # rounds to neares int
+

random variables

+
np.random.normal(loc=0, scale=2, size=100)  # 100 normal distributed random numbers
+np.random.seed(23032)                       # resets the seed value
+np.random.rand(200)                         # 200 random numbers in [0, 1)
+np.random.uniform(1, 30, 200)               # 200 random numbers in [1, 30)
+np.random.random_integers(1, 15, 300)       # 300 random integers between [1, 15]
- -
-

-Matplotlib

- -

-figures and axes

- -
fig = plt.figure(figsize=(5, 2), facecolor='black')  # initialize figure
-ax = fig.add_subplot(3, 2, 2)                        # add second subplot in a 3 x 2 grid
-fig, axes = plt.subplots(5, 2, figsize=(5, 5))       # return fig and array of axes in a 5 x 2 grid
-ax = fig.add_axes([left, bottom, width, height])     # manually add axes at a certain position
- -

-figures and axes properties

- -
fig.suptitle('title')            # big figure title
-fig.subplots_adjust(bottom=0.1, right=0.8, top=0.9, wspace=0.2,
-                    hspace=0.5)  # adjust subplot positions
-fig.tight_layout(pad=0.1,h_pad=0.5, w_pad=0.5, rect=None) # adjust
+
+

Matplotlib

+

figures and axes

+
fig = plt.figure(figsize=(5, 2), facecolor='black')  # initialize figure
+ax = fig.add_subplot(3, 2, 2)                        # add second subplot in a 3 x 2 grid
+fig, axes = plt.subplots(5, 2, figsize=(5, 5))       # return fig and array of axes in a 5 x 2 grid
+ax = fig.add_axes([left, bottom, width, height])     # manually add axes at a certain position
+

figures and axes properties

+
fig.suptitle('title')            # big figure title
+fig.subplots_adjust(bottom=0.1, right=0.8, top=0.9, wspace=0.2,
+                    hspace=0.5)  # adjust subplot positions
+fig.tight_layout(pad=0.1,h_pad=0.5, w_pad=0.5, rect=None) # adjust
 subplots to fit perfectly into fig
-ax.set_xlabel()                  # set xlabel
-ax.set_ylabel()                  # set ylabel
-ax.set_xlim(1, 2)                # sets x limits
-ax.set_ylim(3, 4)                # sets y limits
-ax.set_title('blabla')           # sets the axis title
-ax.set(xlabel='bla')             # set multiple parameters at once
-ax.legend(loc='upper center')    # activate legend
-ax.grid(True, which='both')      # activate grid
-bbox = ax.get_position()         # returns the axes bounding box
-bbox.x0 + bbox.width             # bounding box parameters
- -

-plotting routines

+ax.set_xlabel() # set xlabel +ax.set_ylabel() # set ylabel +ax.set_xlim(1, 2) # sets x limits +ax.set_ylim(3, 4) # sets y limits +ax.set_title('blabla') # sets the axis title +ax.set(xlabel='bla') # set multiple parameters at once +ax.legend(loc='upper center') # activate legend +ax.grid(True, which='both') # activate grid +bbox = ax.get_position() # returns the axes bounding box +bbox.x0 + bbox.width # bounding box parameters
+

plotting routines

+
ax.plot(x,y, '-o', c='red', lw=2, label='bla')  # plots a line
+ax.scatter(x,y, s=20, c=color)                  # scatter plot
+ax.pcolormesh(xx,yy,zz, shading='gouraud')      # fast colormesh function
+ax.colormesh(xx,yy,zz, norm=norm)               # slower colormesh function
+ax.contour(xx,yy,zz, cmap='jet')                # contour line plot
+ax.contourf(xx,yy,zz, vmin=2, vmax=4)           # filled contours plot
+n, bins, patch = ax.hist(x, 50)                 # histogram
+ax.imshow(matrix, origin='lower', extent=(x1, x2, y1, y2))  # show image
+ax.specgram(y, FS=0.1, noverlap=128, scale='linear')  # plot a spectrogram
-
ax.plot(x,y, '-o', c='red', lw=2, label='bla')  # plots a line
-ax.scatter(x,y, s=20, c=color)                  # scatter plot
-ax.pcolormesh(xx,yy,zz, shading='gouraud')      # fast colormesh function
-ax.colormesh(xx,yy,zz, norm=norm)               # slower colormesh function
-ax.contour(xx,yy,zz, cmap='jet')                # contour line plot
-ax.contourf(xx,yy,zz, vmin=2, vmax=4)           # filled contours plot
-n, bins, patch = ax.hist(x, 50)                 # histogram
-ax.imshow(matrix, origin='lower', extent=(x1, x2, y1, y2))  # show image
-ax.specgram(y, FS=0.1, noverlap=128, scale='linear')  # plot a spectrogram
@@ -428,7 +345,6 @@

- - + From 6657db991a42ed466096e29490b743b67ec17c23 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 25 Apr 2016 15:26:57 +0200 Subject: [PATCH 17/96] added gitignore --- .gitignore | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7a68821 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +# ignore tex compilation files (created by emacs and latex) +*.aux +*.log +*.gz +auto/* + +# ignore stuffs generated by jelykk while serving the site locally +_site +_site/* From bb42bd0d7caa7a648f5f45f00ed57e9bdc5ea35e Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 25 Apr 2016 15:52:24 +0200 Subject: [PATCH 18/96] regenerad website revision: 4502ce7 --- index.html | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/index.html b/index.html index 2297c48..ca8d3cf 100644 --- a/index.html +++ b/index.html @@ -17,14 +17,14 @@ table.sourceCode { width: 100%; line-height: 100%; } td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; background-color: #dddddd; } td.sourceCode { padding-left: 5px; } -code > span.kw { font-weight: bold; } /* Keyword */ +code > span.kw { color: #a71d5d } /* Keyword */ code > span.dt { color: #800000; } /* DataType */ -code > span.dv { color: #0000ff; } /* DecVal */ -code > span.bn { color: #0000ff; } /* BaseN */ -code > span.fl { color: #800080; } /* Float */ -code > span.ch { color: #ff00ff; } /* Char */ -code > span.st { color: #dd0000; } /* String */ -code > span.co { color: #808080; font-style: italic; } /* Comment */ +code > span.dv { color: #ed6a43; } /* DecVal */ +code > span.bn { color: #ed6a43; } /* BaseN */ +code > span.fl { color: #ed6a43; } /* Float */ +code > span.ch { color: #ed6a43; } /* Char */ +code > span.st { color: #0086b3; } /* String */ +code > span.co { color: #969896 } /* Comment */ code > span.al { color: #00ff00; font-weight: bold; } /* Alert */ code > span.fu { color: #000080; } /* Function */ code > span.er { color: #ff0000; font-weight: bold; } /* Error */ From 15ec1c582d992a87b76d78afd83474ec22692810 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 25 Apr 2016 16:15:58 +0200 Subject: [PATCH 19/96] regenerad website revision: 03d7870 --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index ca8d3cf..de47c74 100644 --- a/index.html +++ b/index.html @@ -29,7 +29,7 @@ code > span.fu { color: #000080; } /* Function */ code > span.er { color: #ff0000; font-weight: bold; } /* Error */ code > span.wa { color: #ff0000; font-weight: bold; } /* Warning */ -code > span.cn { color: #000000; } /* Constant */ +code > span.cn { color: #0086b3; } /* Constant */ code > span.sc { color: #ff00ff; } /* SpecialChar */ code > span.vs { color: #dd0000; } /* VerbatimString */ code > span.ss { color: #dd0000; } /* SpecialString */ From 257e6b7e2afa863da7ba0f46bccd2dd3f98dcdab Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 25 Apr 2016 16:57:12 +0200 Subject: [PATCH 20/96] regenerad website revision: 912c544 --- index.html | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/index.html b/index.html index de47c74..3640aa0 100644 --- a/index.html +++ b/index.html @@ -19,11 +19,11 @@ td.sourceCode { padding-left: 5px; } code > span.kw { color: #a71d5d } /* Keyword */ code > span.dt { color: #800000; } /* DataType */ -code > span.dv { color: #ed6a43; } /* DecVal */ -code > span.bn { color: #ed6a43; } /* BaseN */ -code > span.fl { color: #ed6a43; } /* Float */ -code > span.ch { color: #ed6a43; } /* Char */ -code > span.st { color: #0086b3; } /* String */ +code > span.dv { color: #009999; } /* DecVal */ +code > span.bn { color: #009999; } /* BaseN */ +code > span.fl { color: #009999; } /* Float */ +code > span.ch { color: #009999 ; } /* Char */ +code > span.st { color: #d01040; } /* String */ code > span.co { color: #969896 } /* Comment */ code > span.al { color: #00ff00; font-weight: bold; } /* Alert */ code > span.fu { color: #000080; } /* Function */ @@ -33,11 +33,11 @@ code > span.sc { color: #ff00ff; } /* SpecialChar */ code > span.vs { color: #dd0000; } /* VerbatimString */ code > span.ss { color: #dd0000; } /* SpecialString */ -code > span.im { } /* Import */ -code > span.va { } /* Variable */ -code > span.cf { } /* ControlFlow */ -code > span.op { } /* Operator */ -code > span.bu { } /* BuiltIn */ +code > span.im {color: #000000; font-weight: bold; } /* Import */ +code > span.va {color: #000000; font-weight: bold; } /* Variable */ +code > span.cf {color: #000000; font-weight: bold; } /* ControlFlow */ +code > span.op {color: #000000; font-weight: bold; } /* Operator */ +code > span.bu {color: #0086B3; } /* BuiltIn */ code > span.ex { } /* Extension */ code > span.pp { font-weight: bold; } /* Preprocessor */ code > span.at { } /* Attribute */ From 1a8c1a44db03cc2372049bb347a67e6bdb539772 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 25 Apr 2016 17:02:27 +0200 Subject: [PATCH 21/96] regenerad website revision: 2bb5754 --- index.html | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/index.html b/index.html index 3640aa0..c0c7388 100644 --- a/index.html +++ b/index.html @@ -33,10 +33,10 @@ code > span.sc { color: #ff00ff; } /* SpecialChar */ code > span.vs { color: #dd0000; } /* VerbatimString */ code > span.ss { color: #dd0000; } /* SpecialString */ -code > span.im {color: #000000; font-weight: bold; } /* Import */ -code > span.va {color: #000000; font-weight: bold; } /* Variable */ -code > span.cf {color: #000000; font-weight: bold; } /* ControlFlow */ -code > span.op {color: #000000; font-weight: bold; } /* Operator */ +code > span.im {color: #000080; } /* Import */ +code > span.va {color: #000080; } /* Variable */ +code > span.cf {color: #000080; } /* ControlFlow */ +code > span.op {color: #000080; } /* Operator */ code > span.bu {color: #0086B3; } /* BuiltIn */ code > span.ex { } /* Extension */ code > span.pp { font-weight: bold; } /* Preprocessor */ From f3edc3789a212700b9706f6fcc4efe3288e10e16 Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 25 Apr 2016 17:38:45 +0200 Subject: [PATCH 22/96] regenerad website revision: f4ff9ad --- index.html | 673 +++++++++++++++++++++++------------------------------ 1 file changed, 294 insertions(+), 379 deletions(-) diff --git a/index.html b/index.html index fcf3a61..cc8614a 100644 --- a/index.html +++ b/index.html @@ -1,3 +1,4 @@ + @@ -8,54 +9,63 @@ + +
-

-Scientific Python Cheatsheet

-

Table of Contents

+

Scientific Python Cheatsheet

+
  • Matplotlib
  • + - - - - - - - -
    -

    -Pure Python

    - -

    -Types

    - -
    a = 2           # integer
    -b = 5.0         # float
    -c = 8.3e5       # exponential
    -d = 1.5 + 0.5j  # complex
    -e = 3 > 4       # boolean
    -f = 'word'      # string
    - -

    -Lists

    - -
    a = ['red', 'blue', 'green']      # manually initialization
    -b = range(5)                      # initialization through a function
    -c = [nu**2 for nu in b]           # initialize through list comprehension
    -d = [nu**2 for nu in b if b < 3]  # list comprehension withcondition
    -e = c[0]                          # access element
    -f = e[1: 2]                       # access a slice of the list
    -g = ['re', 'bl'] + ['gr']         # list concatenation
    -h = ['re'] * 5                    # repeat a list
    -['re', 'bl'].index('re')          # returns index of 're'
    -'re' in ['re', 'bl']              # true if 're' in list
    -sorted([3, 2, 1])                 # returns sorted list
    -z = ['red'] + ['green', 'blue']   # list concatenation
    - -

    -Dictionaries

    - -
    a = {'red': 'rouge', 'blue': 'bleu', 'green': 'vert'}  # dictionary
    -b = a['red']                                           # translate item
    -c = [value for key, value in b.items()]                # loop through contents
    -d = a.get('yellow', 'no translation found')            # return default
    - -

    -Strings

    - -
    a = 'red'                      # assignment
    -char = a[2]                    # access individual characters
    -'red ' + 'blue'                # string concatenation
    -'1, 2, three'.split(',')       # split string into list
    -'.'.join(['1', '2', 'three'])  # concatenate list into string
    - -

    -Operators

    - -
    a = 2             # assignment
    -a += 1 (*=, /=)   # change and assign
    -3 + 2             # addition
    -3 / 2             # integer division (python2) or float division (python3)
    -3 // 2            # integer division
    -3 * 2             # multiplication
    -3 ** 2            # exponent
    -3 % 2             # remainder
    -abs()             # absolute value
    -1 == 1            # equal
    -2 > 1             # larger
    -2 < 1             # smaller
    -1 != 2            # not equal
    -1 != 2 and 2 < 3  # logical AND
    -1 != 2 or 2 < 3   # logical OR
    -not 1 == 2        # logical NOT
    -a in b            # test if a is in b
    -a is b            # test if objects point to the same memory (id)
    - -

    -Control Flow

    - -

    -if/elif/else

    - -
    a, b = 1, 2
    -if a + b == 3:
    -    print 'True'
    -elif a + b == 1:
    -    print 'False'
    -else:
    -    print '?'
    - -

    -for

    - -
    a = ['red', 'blue',
    -     'green']
    -for color in a:
    -    print color
    - -

    -while

    - -
    number = 1
    -while number < 10:
    -    print number
    -    number += 1
    - -

    -break

    - -
    number = 1
    -while True:
    -    print number
    -    number += 1
    -    if number > 10:
    -        break
    - -

    -continue

    - -
    for i in range(20):
    -    if i % 2 == 0:
    -        continue
    -    print i
    - -

    -Functions, Classes, Generators, Decorators

    - -

    -Function

    - -
    def myfunc(a1, a2):
    -    return x
    -
    -x = my_function(a1,a2)
    - -

    -Class

    - -
    class Point(object):
    -    def __init__(self, x):
    -        self.x = x
    -    def __call__(self):
    -        print self.x
    -
    -x = Point(3)
    - -

    -Generators

    - -
    def firstn(n):
    -    num = 0
    -    while num < n:
    -        yield num
    -        num += 1
    -
    -x = [for i in firstn(10)]
    - -

    -Decorators

    - -
    class myDecorator(object):
    -    def __init__(self, f):
    -        self.f = f
    -    def __call__(self):
    -        print "call"
    -        self.f()
    -
    -@myDecorator
    -def my_funct():
    -    print 'func'
    -
    -my_func()
    +
    +

    Pure Python

    +

    Types

    +
    a = 2           # integer
    +b = 5.0         # float
    +c = 8.3e5       # exponential
    +d = 1.5 + 0.5j  # complex
    +e = 4 > 5       # boolean
    +f = 'word'      # string
    +

    Lists

    +
    a = ['red', 'blue', 'green']      # manually initialization
    +b = range(5)                      # initialization through a function
    +c = [nu**2 for nu in b]           # initialize through list comprehension
    +d = [nu**2 for nu in b if b < 3]  # list comprehension withcondition
    +e = c[0]                          # access element
    +f = e[1: 2]                       # access a slice of the list
    +g = ['re', 'bl'] + ['gr']         # list concatenation
    +h = ['re'] * 5                    # repeat a list
    +['re', 'bl'].index('re')          # returns index of 're'
    +'re' in ['re', 'bl']              # true if 're' in list
    +sorted([3, 2, 1])                 # returns sorted list
    +z = ['red'] + ['green', 'blue']   # list concatenation
    +

    Dictionaries

    +
    a = {'red': 'rouge', 'blue': 'bleu', 'green': 'vert'}  # dictionary
    +b = a['red']                                           # translate item
    +c = [value for key, value in b.items()]                # loop through contents
    +d = a.get('yellow', 'no translation found')            # return default
    +

    Strings

    +
    a = 'red'                      # assignment
    +char = a[2]                    # access individual characters
    +'red ' + 'blue'                # string concatenation
    +'1, 2, three'.split(',')       # split string into list
    +'.'.join(['1', '2', 'three'])  # concatenate list into string
    +

    Operators

    +
    a = 2             # assignment
    +a += 1 (*=, /=)   # change and assign
    +3 + 2             # addition
    +3 / 2             # integer division (python2) or float division (python3)
    +3 // 2            # integer division
    +3 * 2             # multiplication
    +3 ** 2            # exponent
    +3 % 2             # remainder
    +abs()             # absolute value
    +1 == 1            # equal
    +2 > 1             # larger
    +2 < 1             # smaller
    +1 != 2            # not equal
    +1 != 2 and 2 < 3  # logical AND
    +1 != 2 or 2 < 3   # logical OR
    +not 1 == 2        # logical NOT
    +a in b            # test if a is in b
    +a is b            # test if objects point to the same memory (id)
    +

    Control Flow

    +
    # if/elif/else
    +a, b = 1, 2
    +if a + b == 3:
    +    print 'True'
    +elif a + b == 1:
    +    print 'False'
    +else:
    +    print '?'
    +
    +# for
    +a = ['red', 'blue', 'green']
    +for color in a:
    +    print color
    +
    +# while
    +number = 1
    +while number < 10:
    +    print number
    +    number += 1
    +
    +# break
    +number = 1
    +while True:
    +    print number
    +    number += 1
    +    if number > 10:
    +        break
    +
    +# continue
    +for i in range(20):
    +    if i % 2 == 0:
    +        continue
    +    print i
    +

    Functions, Classes, Generators, Decorators

    +
    # Function
    +def myfunc(a1, a2):
    +    return x
    +
    +x = my_function(a1,a2)
    +
    +# Class
    +class Point(object):
    +    def __init__(self, x):
    +        self.x = x
    +    def __call__(self):
    +        print self.x
    +
    +x = Point(3)
    +
    +# Generators
    +def firstn(n):
    +    num = 0
    +    while num < n:
    +        yield num
    +        num += 1
    +
    +x = [for i in firstn(10)]
    +
    +# Decorators
    +class myDecorator(object):
    +    def __init__(self, f):
    +        self.f = f
    +    def __call__(self):
    +        print "call"
    +        self.f()
    +
    +@myDecorator
    +def my_funct():
    +    print 'func'
    +
    +my_func()
    - -
    -

    -NumPy

    - -

    -array initialization

    - -
    np.array([2, 3, 4])             # direct initialization
    -np.empty(20, dtype=np.float32)  # single precision array with 20 entries
    -np.zeros(200)                   # initialize 200 zeros
    -np.ones((3,3), dtype=np.int32)  # 3 x 3 integer matrix with ones
    -np.eye(200)                     # ones on the diagonal
    -np.zeros_like(a)                # returns array with zeros and the shape of a
    -np.linspace(0., 10., 100)       # 100 points from 0 to 10
    -np.arange(0, 100, 2)            # points from 0 to <100 with step width 2
    -np.logspace(-5, 2, 100)         # 100 log-spaced points between 1e-5 and 1e2
    -np.copy(a)                      # copy array to new memory
    - -

    -reading/ writing files

    - -
    np.fromfile(fname/object, dtype=np.float32, count=5)  # read binary data from file
    -np.loadtxt(fname/object, skiprows=2, delimiter=',')   # read ascii data from file
    - -

    -array properties and operations

    - -
    a.shape                # a tuple with the lengths of each axis
    -len(a)                 # length of axis 0
    -a.ndim                 # number of dimensions (axes)
    -a.sort(axis=1)         # sort array along axis
    -a.flatten()            # collapse array to one dimension
    -a.conj()               # return complex conjugate
    -a.astype(np.int16)     # cast to integer
    -np.argmax(a, axis=2)   # return index of maximum along a given axis
    -np.cumsum(a)           # return cumulative sum
    -np.any(a)              # True if any element is True
    -np.all(a)              # True if all elements are True
    -np.argsort(a, axis=1)  # return sorted index array along axis
    - -

    -indexing

    - -
    a = np.arange(100)          # initialization with 0 - 99
    -a[: 3] = 0                  # set the first three indices to zero
    -a[1: 5] = 1                 # set indices 1-4 to 1
    -a[start:stop:step]          # general form of indexing/slicing
    -a[None, :]                  # transform to column vector
    -a[[1, 1, 3, 8]]             # return array with values of the indices
    -a = a.reshape(10, 10)       # transform to 10 x 10 matrix
    -a.T                         # return transposed view
    -np.transpose(a, (2, 1, 0))  # transpose array to new axis order
    -a[a < 2]                    # returns array that fulfills elementwise condition
    - -

    -boolean arrays

    - -
    a < 2                          # returns array with boolean values
    -np.logical_and(a < 2, b > 10)  # elementwise logical and
    -np.logical_or(a < 2, b > 10)   # elementwise logical or
    -~a                             # invert boolean array
    -np.invert(a)                   # invert boolean array
    - -

    -elementwise operations and math functions

    - -
    a * 5              # multiplication with scalar
    -a + 5              # addition with scalar
    -a + b              # addition with array b
    -a / b              # division with b (np.NaN for division by zero)
    -np.exp(a)          # exponential (complex and real)
    -np.sin(a)          # sine
    -np.cos(a)          # cosine
    -np.arctan2(y,x)    # arctan(y/x)
    -np.arcsin(x)       # arcsin
    -np.radians(a)      # degrees to radians
    -np.degrees(a)      # radians to degrees
    -np.var(a)          # variance of array
    -np.std(a, axis=1)  # standard deviation
    - -

    -inner / outer products

    - -
    np.dot(a, b)                        # inner matrix product: a_mi b_in
    -np.einsum('ijkl,klmn->ijmn', a, b)  # einstein summation convention
    -np.sum(a, axis=1)                   # sum over axis 1
    -np.abs(a)                           # return array with absolute values
    -a[None, :] + b[:, None]             # outer sum
    -a[None, :] * b[None, :]             # outer product
    -np.outer(a, b)                      # outer product
    -np.sum(a * a.T)                     # matrix norm
    - -

    -interpolation, integration

    - -
    np.trapz(y, x=x, axis=1)  # integrate along axis 1
    -np.interp(x, xp, yp)      # interpolate function xp, yp at points x
    - -

    -fft

    - -
    np.fft.fft(y)             # complex fourier transform of y
    -np.fft.fftfreqs(len(y))   # fft frequencies for a given length
    -np.fft.fftshift(freqs)    # shifts zero frequency to the middle
    -np.fft.rfft(y)            # real fourier transform of y
    -np.fft.rfftfreqs(len(y))  # real fft frequencies for a given length
    - -

    -rounding

    - -
    np.ceil(a)   # rounds to nearest upper int
    -np.floor(a)  # rounds to nearest lower int
    -np.round(a)  # rounds to neares int
    - -

    -random variables

    - -
    np.random.normal(loc=0, scale=2, size=100)  # 100 normal distributed random numbers
    -np.random.seed(23032)                       # resets the seed value
    -np.random.rand(200)                         # 200 random numbers in [0, 1)
    -np.random.uniform(1, 30, 200)               # 200 random numbers in [1, 30)
    -np.random.random_integers(1, 15, 300)       # 300 random integers between [1, 15]
    +
    +

    NumPy

    +

    array initialization

    +
    np.array([2, 3, 4])             # direct initialization
    +np.empty(20, dtype=np.float32)  # single precision array with 20 entries
    +np.zeros(200)                   # initialize 200 zeros
    +np.ones((3,3), dtype=np.int32)  # 3 x 3 integer matrix with ones
    +np.eye(200)                     # ones on the diagonal
    +np.zeros_like(a)                # returns array with zeros and the shape of a
    +np.linspace(0., 10., 100)       # 100 points from 0 to 10
    +np.arange(0, 100, 2)            # points from 0 to <100 with step width 2
    +np.logspace(-5, 2, 100)         # 100 log-spaced points between 1e-5 and 1e2
    +np.copy(a)                      # copy array to new memory
    +

    reading/ writing files

    +
    np.fromfile(fname/object, dtype=np.float32, count=5)  # read binary data from file
    +np.loadtxt(fname/object, skiprows=2, delimiter=',')   # read ascii data from file
    +

    array properties and operations

    +
    a.shape                # a tuple with the lengths of each axis
    +len(a)                 # length of axis 0
    +a.ndim                 # number of dimensions (axes)
    +a.sort(axis=1)         # sort array along axis
    +a.flatten()            # collapse array to one dimension
    +a.conj()               # return complex conjugate
    +a.astype(np.int16)     # cast to integer
    +np.argmax(a, axis=2)   # return index of maximum along a given axis
    +np.cumsum(a)           # return cumulative sum
    +np.any(a)              # True if any element is True
    +np.all(a)              # True if all elements are True
    +np.argsort(a, axis=1)  # return sorted index array along axis
    +

    indexing

    +
    a = np.arange(100)          # initialization with 0 - 99
    +a[: 3] = 0                  # set the first three indices to zero
    +a[1: 5] = 1                 # set indices 1-4 to 1
    +a[start:stop:step]          # general form of indexing/slicing
    +a[None, :]                  # transform to column vector
    +a[[1, 1, 3, 8]]             # return array with values of the indices
    +a = a.reshape(10, 10)       # transform to 10 x 10 matrix
    +a.T                         # return transposed view
    +np.transpose(a, (2, 1, 0))  # transpose array to new axis order
    +a[a < 2]                    # returns array that fulfills elementwise condition
    +

    boolean arrays

    +
    a < 2                          # returns array with boolean values
    +np.logical_and(a < 2, b > 10)  # elementwise logical and
    +np.logical_or(a < 2, b > 10)   # elementwise logical or
    +~a                             # invert boolean array
    +np.invert(a)                   # invert boolean array
    +

    elementwise operations and math functions

    +
    a * 5              # multiplication with scalar
    +a + 5              # addition with scalar
    +a + b              # addition with array b
    +a / b              # division with b (np.NaN for division by zero)
    +np.exp(a)          # exponential (complex and real)
    +np.sin(a)          # sine
    +np.cos(a)          # cosine
    +np.arctan2(y,x)    # arctan(y/x)
    +np.arcsin(x)       # arcsin
    +np.radians(a)      # degrees to radians
    +np.degrees(a)      # radians to degrees
    +np.var(a)          # variance of array
    +np.std(a, axis=1)  # standard deviation
    +

    inner / outer products

    +
    np.dot(a, b)                        # inner matrix product: a_mi b_in
    +np.einsum('ijkl,klmn->ijmn', a, b)  # einstein summation convention
    +np.sum(a, axis=1)                   # sum over axis 1
    +np.abs(a)                           # return array with absolute values
    +a[None, :] + b[:, None]             # outer sum
    +a[None, :] * b[None, :]             # outer product
    +np.outer(a, b)                      # outer product
    +np.sum(a * a.T)                     # matrix norm
    +

    interpolation, integration

    +
    np.trapz(y, x=x, axis=1)  # integrate along axis 1
    +np.interp(x, xp, yp)      # interpolate function xp, yp at points x
    +

    fft

    +
    np.fft.fft(y)             # complex fourier transform of y
    +np.fft.fftfreqs(len(y))   # fft frequencies for a given length
    +np.fft.fftshift(freqs)    # shifts zero frequency to the middle
    +np.fft.rfft(y)            # real fourier transform of y
    +np.fft.rfftfreqs(len(y))  # real fft frequencies for a given length
    +

    rounding

    +
    np.ceil(a)   # rounds to nearest upper int
    +np.floor(a)  # rounds to nearest lower int
    +np.round(a)  # rounds to neares int
    +

    random variables

    +
    np.random.normal(loc=0, scale=2, size=100)  # 100 normal distributed random numbers
    +np.random.seed(23032)                       # resets the seed value
    +np.random.rand(200)                         # 200 random numbers in [0, 1)
    +np.random.uniform(1, 30, 200)               # 200 random numbers in [1, 30)
    +np.random.random_integers(1, 15, 300)       # 300 random integers between [1, 15]
    - -
    -

    -Matplotlib

    - -

    -figures and axes

    - -
    fig = plt.figure(figsize=(5, 2), facecolor='black')  # initialize figure
    -ax = fig.add_subplot(3, 2, 2)                        # add second subplot in a 3 x 2 grid
    -fig, axes = plt.subplots(5, 2, figsize=(5, 5))       # return fig and array of axes in a 5 x 2 grid
    -ax = fig.add_axes([left, bottom, width, height])     # manually add axes at a certain position
    - -

    -figures and axes properties

    - -
    fig.suptitle('title')            # big figure title
    -fig.subplots_adjust(bottom=0.1, right=0.8, top=0.9, wspace=0.2,
    -                    hspace=0.5)  # adjust subplot positions
    -fig.tight_layout(pad=0.1,h_pad=0.5, w_pad=0.5, rect=None) # adjust
    +
    +

    Matplotlib

    +

    figures and axes

    +
    fig = plt.figure(figsize=(5, 2), facecolor='black')  # initialize figure
    +ax = fig.add_subplot(3, 2, 2)                        # add second subplot in a 3 x 2 grid
    +fig, axes = plt.subplots(5, 2, figsize=(5, 5))       # return fig and array of axes in a 5 x 2 grid
    +ax = fig.add_axes([left, bottom, width, height])     # manually add axes at a certain position
    +

    figures and axes properties

    +
    fig.suptitle('title')            # big figure title
    +fig.subplots_adjust(bottom=0.1, right=0.8, top=0.9, wspace=0.2,
    +                    hspace=0.5)  # adjust subplot positions
    +fig.tight_layout(pad=0.1,h_pad=0.5, w_pad=0.5, rect=None) # adjust
     subplots to fit perfectly into fig
    -ax.set_xlabel()                  # set xlabel
    -ax.set_ylabel()                  # set ylabel
    -ax.set_xlim(1, 2)                # sets x limits
    -ax.set_ylim(3, 4)                # sets y limits
    -ax.set_title('blabla')           # sets the axis title
    -ax.set(xlabel='bla')             # set multiple parameters at once
    -ax.legend(loc='upper center')    # activate legend
    -ax.grid(True, which='both')      # activate grid
    -bbox = ax.get_position()         # returns the axes bounding box
    -bbox.x0 + bbox.width             # bounding box parameters
    - -

    -plotting routines

    +ax.set_xlabel() # set xlabel +ax.set_ylabel() # set ylabel +ax.set_xlim(1, 2) # sets x limits +ax.set_ylim(3, 4) # sets y limits +ax.set_title('blabla') # sets the axis title +ax.set(xlabel='bla') # set multiple parameters at once +ax.legend(loc='upper center') # activate legend +ax.grid(True, which='both') # activate grid +bbox = ax.get_position() # returns the axes bounding box +bbox.x0 + bbox.width # bounding box parameters
    +

    plotting routines

    +
    ax.plot(x,y, '-o', c='red', lw=2, label='bla')  # plots a line
    +ax.scatter(x,y, s=20, c=color)                  # scatter plot
    +ax.pcolormesh(xx,yy,zz, shading='gouraud')      # fast colormesh function
    +ax.colormesh(xx,yy,zz, norm=norm)               # slower colormesh function
    +ax.contour(xx,yy,zz, cmap='jet')                # contour line plot
    +ax.contourf(xx,yy,zz, vmin=2, vmax=4)           # filled contours plot
    +n, bins, patch = ax.hist(x, 50)                 # histogram
    +ax.imshow(matrix, origin='lower', extent=(x1, x2, y1, y2))  # show image
    +ax.specgram(y, FS=0.1, noverlap=128, scale='linear')  # plot a spectrogram
    -
    ax.plot(x,y, '-o', c='red', lw=2, label='bla')  # plots a line
    -ax.scatter(x,y, s=20, c=color)                  # scatter plot
    -ax.pcolormesh(xx,yy,zz, shading='gouraud')      # fast colormesh function
    -ax.colormesh(xx,yy,zz, norm=norm)               # slower colormesh function
    -ax.contour(xx,yy,zz, cmap='jet')                # contour line plot
    -ax.contourf(xx,yy,zz, vmin=2, vmax=4)           # filled contours plot
    -n, bins, patch = ax.hist(x, 50)                 # histogram
    -ax.imshow(matrix, origin='lower', extent=(x1, x2, y1, y2))  # show image
    -ax.specgram(y, FS=0.1, noverlap=128, scale='linear')  # plot a spectrogram
    @@ -428,7 +344,6 @@

    - - + From 0b48c79cfd9890306746e8e38946d75cf33af5e5 Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 25 Apr 2016 17:42:14 +0200 Subject: [PATCH 23/96] regenerad website revision: 1f818f6 --- index.html | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/index.html b/index.html index cc8614a..d8d944f 100644 --- a/index.html +++ b/index.html @@ -87,7 +87,7 @@

    Scientific Python Cheatsheet

    -
    +

    Pure Python

    Types

    a = 2           # integer
    @@ -212,7 +212,7 @@ 

    Functions, Classes, Generators, my_func()

    -
    +

    NumPy

    array initialization

    np.array([2, 3, 4])             # direct initialization
    @@ -301,7 +301,7 @@ 

    random variables

    np.random.uniform(1, 30, 200) # 200 random numbers in [1, 30) np.random.random_integers(1, 15, 300) # 300 random integers between [1, 15]
    -
    +

    Matplotlib

    figures and axes

    fig = plt.figure(figsize=(5, 2), facecolor='black')  # initialize figure
    
    From 345dcbcbf5dc85c472889d9a9078cd69324a879d Mon Sep 17 00:00:00 2001
    From: Thomas Belahi 
    Date: Tue, 26 Apr 2016 09:35:05 +0200
    Subject: [PATCH 24/96] regenerad website revision: e30c376
    
    ---
     index.html | 350 +++++++++++++++++++++++++++++++++++++++++++++++++++++
     1 file changed, 350 insertions(+)
    
    diff --git a/index.html b/index.html
    index e69de29..00c71b9 100644
    --- a/index.html
    +++ b/index.html
    @@ -0,0 +1,350 @@
    +
    +
    +
    +  
    +    
    +    Scientific python cheat sheet by IPGP
    +    
    +    
    +    
    +    
    +    
    +      
    +  
    +  
    +  
    +    
    + + +

    Scientific Python Cheatsheet

    +

    Table of Contents

    + +
    +

    Pure Python

    +

    Types

    +
    a = 2           # integer
    +b = 5.0         # float
    +c = 8.3e5       # exponential
    +d = 1.5 + 0.5j  # complex
    +e = 4 > 5       # boolean
    +f = 'word'      # string
    +

    Lists

    +
    a = ['red', 'blue', 'green']      # manually initialization
    +b = range(5)                      # initialization through a function
    +c = [nu**2 for nu in b]           # initialize through list comprehension
    +d = [nu**2 for nu in b if b < 3]  # list comprehension withcondition
    +e = c[0]                          # access element
    +f = e[1: 2]                       # access a slice of the list
    +g = ['re', 'bl'] + ['gr']         # list concatenation
    +h = ['re'] * 5                    # repeat a list
    +['re', 'bl'].index('re')          # returns index of 're'
    +'re' in ['re', 'bl']              # true if 're' in list
    +sorted([3, 2, 1])                 # returns sorted list
    +z = ['red'] + ['green', 'blue']   # list concatenation
    +

    Dictionaries

    +
    a = {'red': 'rouge', 'blue': 'bleu', 'green': 'vert'}  # dictionary
    +b = a['red']                                           # translate item
    +c = [value for key, value in b.items()]                # loop through contents
    +d = a.get('yellow', 'no translation found')            # return default
    +

    Strings

    +
    a = 'red'                      # assignment
    +char = a[2]                    # access individual characters
    +'red ' + 'blue'                # string concatenation
    +'1, 2, three'.split(',')       # split string into list
    +'.'.join(['1', '2', 'three'])  # concatenate list into string
    +

    Operators

    +
    a = 2             # assignment
    +a += 1 (*=, /=)   # change and assign
    +3 + 2             # addition
    +3 / 2             # integer division (python2) or float division (python3)
    +3 // 2            # integer division
    +3 * 2             # multiplication
    +3 ** 2            # exponent
    +3 % 2             # remainder
    +abs()             # absolute value
    +1 == 1            # equal
    +2 > 1             # larger
    +2 < 1             # smaller
    +1 != 2            # not equal
    +1 != 2 and 2 < 3  # logical AND
    +1 != 2 or 2 < 3   # logical OR
    +not 1 == 2        # logical NOT
    +a in b            # test if a is in b
    +a is b            # test if objects point to the same memory (id)
    +

    Control Flow

    +
    # if/elif/else
    +a, b = 1, 2
    +if a + b == 3:
    +    print 'True'
    +elif a + b == 1:
    +    print 'False'
    +else:
    +    print '?'
    +    
    +# for
    +a = ['red', 'blue', 'green']
    +for color in a:
    +    print color
    +    
    +# while
    +number = 1
    +while number < 10:
    +    print number
    +    number += 1
    +
    +# break
    +number = 1
    +while True:
    +    print number
    +    number += 1
    +    if number > 10:
    +        break
    +
    +# continue
    +for i in range(20):
    +    if i % 2 == 0:
    +        continue
    +    print i
    +

    Functions, Classes, Generators, Decorators

    +
    # Function
    +def myfunc(a1, a2):
    +    return x
    +
    +x = my_function(a1,a2)
    +
    +# Class
    +class Point(object):
    +    def __init__(self, x):
    +        self.x = x
    +    def __call__(self):
    +        print self.x
    +
    +x = Point(3)
    +
    +# Generators
    +def firstn(n):
    +    num = 0
    +    while num < n:
    +        yield num
    +        num += 1
    +
    +x = [for i in firstn(10)]
    +
    +# Decorators
    +class myDecorator(object):
    +    def __init__(self, f):
    +        self.f = f
    +    def __call__(self):
    +        print "call"
    +        self.f()
    +
    +@myDecorator
    +def my_funct():
    +    print 'func'
    +
    +my_func()
    +
    +
    +

    NumPy

    +

    array initialization

    +
    np.array([2, 3, 4])             # direct initialization
    +np.empty(20, dtype=np.float32)  # single precision array with 20 entries
    +np.zeros(200)                   # initialize 200 zeros
    +np.ones((3,3), dtype=np.int32)  # 3 x 3 integer matrix with ones
    +np.eye(200)                     # ones on the diagonal
    +np.zeros_like(a)                # returns array with zeros and the shape of a
    +np.linspace(0., 10., 100)       # 100 points from 0 to 10
    +np.arange(0, 100, 2)            # points from 0 to <100 with step width 2
    +np.logspace(-5, 2, 100)         # 100 log-spaced points between 1e-5 and 1e2
    +np.copy(a)                      # copy array to new memory
    +

    reading/ writing files

    +
    np.fromfile(fname/object, dtype=np.float32, count=5)  # read binary data from file
    +np.loadtxt(fname/object, skiprows=2, delimiter=',')   # read ascii data from file
    +

    array properties and operations

    +
    a.shape                # a tuple with the lengths of each axis
    +len(a)                 # length of axis 0
    +a.ndim                 # number of dimensions (axes)
    +a.sort(axis=1)         # sort array along axis
    +a.flatten()            # collapse array to one dimension
    +a.conj()               # return complex conjugate
    +a.astype(np.int16)     # cast to integer
    +np.argmax(a, axis=2)   # return index of maximum along a given axis
    +np.cumsum(a)           # return cumulative sum
    +np.any(a)              # True if any element is True
    +np.all(a)              # True if all elements are True
    +np.argsort(a, axis=1)  # return sorted index array along axis
    +

    indexing

    +
    a = np.arange(100)          # initialization with 0 - 99
    +a[: 3] = 0                  # set the first three indices to zero
    +a[1: 5] = 1                 # set indices 1-4 to 1
    +a[start:stop:step]          # general form of indexing/slicing
    +a[None, :]                  # transform to column vector
    +a[[1, 1, 3, 8]]             # return array with values of the indices
    +a = a.reshape(10, 10)       # transform to 10 x 10 matrix
    +a.T                         # return transposed view
    +np.transpose(a, (2, 1, 0))  # transpose array to new axis order
    +a[a < 2]                    # returns array that fulfills elementwise condition
    +

    boolean arrays

    +
    a < 2                          # returns array with boolean values
    +np.logical_and(a < 2, b > 10)  # elementwise logical and
    +np.logical_or(a < 2, b > 10)   # elementwise logical or
    +~a                             # invert boolean array
    +np.invert(a)                   # invert boolean array
    +

    elementwise operations and math functions

    +
    a * 5              # multiplication with scalar
    +a + 5              # addition with scalar
    +a + b              # addition with array b
    +a / b              # division with b (np.NaN for division by zero)
    +np.exp(a)          # exponential (complex and real)
    +np.sin(a)          # sine
    +np.cos(a)          # cosine
    +np.arctan2(y,x)    # arctan(y/x)
    +np.arcsin(x)       # arcsin
    +np.radians(a)      # degrees to radians
    +np.degrees(a)      # radians to degrees
    +np.var(a)          # variance of array
    +np.std(a, axis=1)  # standard deviation
    +

    inner / outer products

    +
    np.dot(a, b)                        # inner matrix product: a_mi b_in
    +np.einsum('ijkl,klmn->ijmn', a, b)  # einstein summation convention
    +np.sum(a, axis=1)                   # sum over axis 1
    +np.abs(a)                           # return array with absolute values
    +a[None, :] + b[:, None]             # outer sum
    +a[None, :] * b[None, :]             # outer product
    +np.outer(a, b)                      # outer product
    +np.sum(a * a.T)                     # matrix norm
    +

    interpolation, integration

    +
    np.trapz(y, x=x, axis=1)  # integrate along axis 1
    +np.interp(x, xp, yp)      # interpolate function xp, yp at points x
    +

    fft

    +
    np.fft.fft(y)             # complex fourier transform of y
    +np.fft.fftfreqs(len(y))   # fft frequencies for a given length
    +np.fft.fftshift(freqs)    # shifts zero frequency to the middle
    +np.fft.rfft(y)            # real fourier transform of y
    +np.fft.rfftfreqs(len(y))  # real fft frequencies for a given length
    +

    rounding

    +
    np.ceil(a)   # rounds to nearest upper int
    +np.floor(a)  # rounds to nearest lower int
    +np.round(a)  # rounds to neares int
    +

    random variables

    +
    np.random.normal(loc=0, scale=2, size=100)  # 100 normal distributed random numbers
    +np.random.seed(23032)                       # resets the seed value
    +np.random.rand(200)                         # 200 random numbers in [0, 1)
    +np.random.uniform(1, 30, 200)               # 200 random numbers in [1, 30)
    +np.random.random_integers(1, 15, 300)       # 300 random integers between [1, 15]
    +
    +
    +

    Matplotlib

    +

    figures and axes

    +
    fig = plt.figure(figsize=(5, 2), facecolor='black')  # initialize figure
    +ax = fig.add_subplot(3, 2, 2)                        # add second subplot in a 3 x 2 grid
    +fig, axes = plt.subplots(5, 2, figsize=(5, 5))       # return fig and array of axes in a 5 x 2 grid
    +ax = fig.add_axes([left, bottom, width, height])     # manually add axes at a certain position
    +

    figures and axes properties

    +
    fig.suptitle('title')            # big figure title
    +fig.subplots_adjust(bottom=0.1, right=0.8, top=0.9, wspace=0.2,
    +                    hspace=0.5)  # adjust subplot positions
    +fig.tight_layout(pad=0.1,h_pad=0.5, w_pad=0.5, rect=None) # adjust
    +subplots to fit perfectly into fig
    +ax.set_xlabel()                  # set xlabel
    +ax.set_ylabel()                  # set ylabel
    +ax.set_xlim(1, 2)                # sets x limits
    +ax.set_ylim(3, 4)                # sets y limits
    +ax.set_title('blabla')           # sets the axis title
    +ax.set(xlabel='bla')             # set multiple parameters at once
    +ax.legend(loc='upper center')    # activate legend
    +ax.grid(True, which='both')      # activate grid
    +bbox = ax.get_position()         # returns the axes bounding box
    +bbox.x0 + bbox.width             # bounding box parameters
    +

    plotting routines

    +
    ax.plot(x,y, '-o', c='red', lw=2, label='bla')  # plots a line
    +ax.scatter(x,y, s=20, c=color)                  # scatter plot
    +ax.pcolormesh(xx,yy,zz, shading='gouraud')      # fast colormesh function
    +ax.colormesh(xx,yy,zz, norm=norm)               # slower colormesh function
    +ax.contour(xx,yy,zz, cmap='jet')                # contour line plot
    +ax.contourf(xx,yy,zz, vmin=2, vmax=4)           # filled contours plot
    +n, bins, patch = ax.hist(x, 50)                 # histogram
    +ax.imshow(matrix, origin='lower', extent=(x1, x2, y1, y2))  # show image
    +ax.specgram(y, FS=0.1, noverlap=128, scale='linear')  # plot a spectrogram
    + +
    + + + +
    + + + From fc15434ef52c0ccefb31c12a660d1b36cfadf667 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Tue, 26 Apr 2016 08:13:13 +0000 Subject: [PATCH 25/96] rebuild pages at 09b4a56 --- .gitignore | 9 - .../github-light.css => github-light.css | 0 index.html | 323 +++++++++--------- stylesheets/normalize.css => normalize.css | 0 stylesheets/stylesheet.css => stylesheet.css | 0 5 files changed, 161 insertions(+), 171 deletions(-) delete mode 100644 .gitignore rename stylesheets/github-light.css => github-light.css (100%) rename stylesheets/normalize.css => normalize.css (100%) rename stylesheets/stylesheet.css => stylesheet.css (100%) diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 7a68821..0000000 --- a/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -# ignore tex compilation files (created by emacs and latex) -*.aux -*.log -*.gz -auto/* - -# ignore stuffs generated by jelykk while serving the site locally -_site -_site/* diff --git a/stylesheets/github-light.css b/github-light.css similarity index 100% rename from stylesheets/github-light.css rename to github-light.css diff --git a/index.html b/index.html index 00c71b9..d8d944f 100644 --- a/index.html +++ b/index.html @@ -52,7 +52,6 @@

    Scientific Python Cheatsheet

    -

    Table of Contents

    • Scientific Python Cheatsheet
        @@ -91,179 +90,179 @@

        Scientific Python Cheatsheet

        Pure Python

        Types

        -
        a = 2           # integer
        -b = 5.0         # float
        -c = 8.3e5       # exponential
        -d = 1.5 + 0.5j  # complex
        -e = 4 > 5       # boolean
        -f = 'word'      # string
        +
        a = 2           # integer
        +b = 5.0         # float
        +c = 8.3e5       # exponential
        +d = 1.5 + 0.5j  # complex
        +e = 4 > 5       # boolean
        +f = 'word'      # string

        Lists

        -
        a = ['red', 'blue', 'green']      # manually initialization
        -b = range(5)                      # initialization through a function
        -c = [nu**2 for nu in b]           # initialize through list comprehension
        -d = [nu**2 for nu in b if b < 3]  # list comprehension withcondition
        -e = c[0]                          # access element
        -f = e[1: 2]                       # access a slice of the list
        -g = ['re', 'bl'] + ['gr']         # list concatenation
        -h = ['re'] * 5                    # repeat a list
        +
        a = ['red', 'blue', 'green']      # manually initialization
        +b = range(5)                      # initialization through a function
        +c = [nu**2 for nu in b]           # initialize through list comprehension
        +d = [nu**2 for nu in b if b < 3]  # list comprehension withcondition
        +e = c[0]                          # access element
        +f = e[1: 2]                       # access a slice of the list
        +g = ['re', 'bl'] + ['gr']         # list concatenation
        +h = ['re'] * 5                    # repeat a list
         ['re', 'bl'].index('re')          # returns index of 're'
        -'re' in ['re', 'bl']              # true if 're' in list
        -sorted([3, 2, 1])                 # returns sorted list
        -z = ['red'] + ['green', 'blue']   # list concatenation
        +'re' in ['re', 'bl'] # true if 're' in list +sorted([3, 2, 1]) # returns sorted list +z = ['red'] + ['green', 'blue'] # list concatenation

    Dictionaries

    -
    a = {'red': 'rouge', 'blue': 'bleu', 'green': 'vert'}  # dictionary
    -b = a['red']                                           # translate item
    -c = [value for key, value in b.items()]                # loop through contents
    -d = a.get('yellow', 'no translation found')            # return default
    +
    a = {'red': 'rouge', 'blue': 'bleu', 'green': 'vert'}  # dictionary
    +b = a['red']                                           # translate item
    +c = [value for key, value in b.items()]                # loop through contents
    +d = a.get('yellow', 'no translation found')            # return default

    Strings

    -
    a = 'red'                      # assignment
    -char = a[2]                    # access individual characters
    -'red ' + 'blue'                # string concatenation
    -'1, 2, three'.split(',')       # split string into list
    -'.'.join(['1', '2', 'three'])  # concatenate list into string
    +
    a = 'red'                      # assignment
    +char = a[2]                    # access individual characters
    +'red ' + 'blue'                # string concatenation
    +'1, 2, three'.split(',')       # split string into list
    +'.'.join(['1', '2', 'three'])  # concatenate list into string

    Operators

    -
    a = 2             # assignment
    -a += 1 (*=, /=)   # change and assign
    -3 + 2             # addition
    -3 / 2             # integer division (python2) or float division (python3)
    -3 // 2            # integer division
    -3 * 2             # multiplication
    -3 ** 2            # exponent
    -3 % 2             # remainder
    -abs()             # absolute value
    -1 == 1            # equal
    -2 > 1             # larger
    -2 < 1             # smaller
    -1 != 2            # not equal
    -1 != 2 and 2 < 3  # logical AND
    -1 != 2 or 2 < 3   # logical OR
    -not 1 == 2        # logical NOT
    -a in b            # test if a is in b
    -a is b            # test if objects point to the same memory (id)
    +
    a = 2             # assignment
    +a += 1 (*=, /=)   # change and assign
    +3 + 2             # addition
    +3 / 2             # integer division (python2) or float division (python3)
    +3 // 2            # integer division
    +3 * 2             # multiplication
    +3 ** 2            # exponent
    +3 % 2             # remainder
    +abs()             # absolute value
    +1 == 1            # equal
    +2 > 1             # larger
    +2 < 1             # smaller
    +1 != 2            # not equal
    +1 != 2 and 2 < 3  # logical AND
    +1 != 2 or 2 < 3   # logical OR
    +not 1 == 2        # logical NOT
    +a in b            # test if a is in b
    +a is b            # test if objects point to the same memory (id)

    Control Flow

    -
    # if/elif/else
    -a, b = 1, 2
    -if a + b == 3:
    -    print 'True'
    -elif a + b == 1:
    -    print 'False'
    -else:
    -    print '?'
    -    
    +
    # if/elif/else
    +a, b = 1, 2
    +if a + b == 3:
    +    print 'True'
    +elif a + b == 1:
    +    print 'False'
    +else:
    +    print '?'
    +
     # for
    -a = ['red', 'blue', 'green']
    -for color in a:
    -    print color
    -    
    +a = ['red', 'blue', 'green']
    +for color in a:
    +    print color
    +
     # while
    -number = 1
    -while number < 10:
    -    print number
    -    number += 1
    +number = 1
    +while number < 10:
    +    print number
    +    number += 1
     
     # break
    -number = 1
    -while True:
    -    print number
    -    number += 1
    -    if number > 10:
    -        break
    +number = 1
    +while True:
    +    print number
    +    number += 1
    +    if number > 10:
    +        break
     
     # continue
    -for i in range(20):
    -    if i % 2 == 0:
    -        continue
    -    print i
    +for i in range(20): + if i % 2 == 0: + continue + print i

    Functions, Classes, Generators, Decorators

    -
    # Function
    +
    # Function
     def myfunc(a1, a2):
    -    return x
    +    return x
     
    -x = my_function(a1,a2)
    +x = my_function(a1,a2)
     
     # Class
    -class Point(object):
    -    def __init__(self, x):
    -        self.x = x
    -    def __call__(self):
    -        print self.x
    +class Point(object):
    +    def __init__(self, x):
    +        self.x = x
    +    def __call__(self):
    +        print self.x
     
    -x = Point(3)
    +x = Point(3)
     
     # Generators
     def firstn(n):
    -    num = 0
    -    while num < n:
    -        yield num
    -        num += 1
    +    num = 0
    +    while num < n:
    +        yield num
    +        num += 1
     
    -x = [for i in firstn(10)]
    +x = [for i in firstn(10)]
     
     # Decorators
    -class myDecorator(object):
    -    def __init__(self, f):
    -        self.f = f
    -    def __call__(self):
    -        print "call"
    -        self.f()
    +class myDecorator(object):
    +    def __init__(self, f):
    +        self.f = f
    +    def __call__(self):
    +        print "call"
    +        self.f()
     
    -@myDecorator
    +@myDecorator
     def my_funct():
    -    print 'func'
    +    print 'func'
     
    -my_func()
    +my_func()

    NumPy

    array initialization

    -
    np.array([2, 3, 4])             # direct initialization
    -np.empty(20, dtype=np.float32)  # single precision array with 20 entries
    +
    np.array([2, 3, 4])             # direct initialization
    +np.empty(20, dtype=np.float32)  # single precision array with 20 entries
     np.zeros(200)                   # initialize 200 zeros
    -np.ones((3,3), dtype=np.int32)  # 3 x 3 integer matrix with ones
    +np.ones((3,3), dtype=np.int32)  # 3 x 3 integer matrix with ones
     np.eye(200)                     # ones on the diagonal
     np.zeros_like(a)                # returns array with zeros and the shape of a
     np.linspace(0., 10., 100)       # 100 points from 0 to 10
     np.arange(0, 100, 2)            # points from 0 to <100 with step width 2
    -np.logspace(-5, 2, 100)         # 100 log-spaced points between 1e-5 and 1e2
    -np.copy(a)                      # copy array to new memory
    +np.logspace(-5, 2, 100) # 100 log-spaced points between 1e-5 and 1e2 +np.copy(a) # copy array to new memory

    reading/ writing files

    -
    np.fromfile(fname/object, dtype=np.float32, count=5)  # read binary data from file
    -np.loadtxt(fname/object, skiprows=2, delimiter=',')   # read ascii data from file
    +
    np.fromfile(fname/object, dtype=np.float32, count=5)  # read binary data from file
    +np.loadtxt(fname/object, skiprows=2, delimiter=',')   # read ascii data from file

    array properties and operations

    -
    a.shape                # a tuple with the lengths of each axis
    -len(a)                 # length of axis 0
    +
    a.shape                # a tuple with the lengths of each axis
    +len(a)                 # length of axis 0
     a.ndim                 # number of dimensions (axes)
    -a.sort(axis=1)         # sort array along axis
    +a.sort(axis=1)         # sort array along axis
     a.flatten()            # collapse array to one dimension
     a.conj()               # return complex conjugate
     a.astype(np.int16)     # cast to integer
    -np.argmax(a, axis=2)   # return index of maximum along a given axis
    +np.argmax(a, axis=2)   # return index of maximum along a given axis
     np.cumsum(a)           # return cumulative sum
    -np.any(a)              # True if any element is True
    -np.all(a)              # True if all elements are True
    -np.argsort(a, axis=1)  # return sorted index array along axis
    +np.any(a) # True if any element is True +np.all(a) # True if all elements are True +np.argsort(a, axis=1) # return sorted index array along axis

    indexing

    -
    a = np.arange(100)          # initialization with 0 - 99
    -a[: 3] = 0                  # set the first three indices to zero
    -a[1: 5] = 1                 # set indices 1-4 to 1
    +
    a = np.arange(100)          # initialization with 0 - 99
    +a[: 3] = 0                  # set the first three indices to zero
    +a[1: 5] = 1                 # set indices 1-4 to 1
     a[start:stop:step]          # general form of indexing/slicing
    -a[None, :]                  # transform to column vector
    +a[None, :]                  # transform to column vector
     a[[1, 1, 3, 8]]             # return array with values of the indices
    -a = a.reshape(10, 10)       # transform to 10 x 10 matrix
    +a = a.reshape(10, 10)       # transform to 10 x 10 matrix
     a.T                         # return transposed view
     np.transpose(a, (2, 1, 0))  # transpose array to new axis order
    -a[a < 2]                    # returns array that fulfills elementwise condition
    +a[a < 2] # returns array that fulfills elementwise condition

    boolean arrays

    -
    a < 2                          # returns array with boolean values
    -np.logical_and(a < 2, b > 10)  # elementwise logical and
    -np.logical_or(a < 2, b > 10)   # elementwise logical or
    -~a                             # invert boolean array
    -np.invert(a)                   # invert boolean array
    +
    a < 2                          # returns array with boolean values
    +np.logical_and(a < 2, b > 10)  # elementwise logical and
    +np.logical_or(a < 2, b > 10)   # elementwise logical or
    +~a                             # invert boolean array
    +np.invert(a)                   # invert boolean array

    elementwise operations and math functions

    -
    a * 5              # multiplication with scalar
    -a + 5              # addition with scalar
    -a + b              # addition with array b
    -a / b              # division with b (np.NaN for division by zero)
    +
    a * 5              # multiplication with scalar
    +a + 5              # addition with scalar
    +a + b              # addition with array b
    +a / b              # division with b (np.NaN for division by zero)
     np.exp(a)          # exponential (complex and real)
     np.sin(a)          # sine
     np.cos(a)          # cosine
    @@ -272,69 +271,69 @@ 

    elementwise operations and ma np.radians(a) # degrees to radians np.degrees(a) # radians to degrees np.var(a) # variance of array -np.std(a, axis=1) # standard deviation

    +np.std(a, axis=1) # standard deviation

    inner / outer products

    -
    np.dot(a, b)                        # inner matrix product: a_mi b_in
    +
    np.dot(a, b)                        # inner matrix product: a_mi b_in
     np.einsum('ijkl,klmn->ijmn', a, b)  # einstein summation convention
    -np.sum(a, axis=1)                   # sum over axis 1
    -np.abs(a)                           # return array with absolute values
    -a[None, :] + b[:, None]             # outer sum
    -a[None, :] * b[None, :]             # outer product
    +np.sum(a, axis=1)                   # sum over axis 1
    +np.abs(a)                           # return array with absolute values
    +a[None, :] + b[:, None]             # outer sum
    +a[None, :] * b[None, :]             # outer product
     np.outer(a, b)                      # outer product
    -np.sum(a * a.T)                     # matrix norm
    +np.sum(a * a.T) # matrix norm

    interpolation, integration

    -
    np.trapz(y, x=x, axis=1)  # integrate along axis 1
    -np.interp(x, xp, yp)      # interpolate function xp, yp at points x
    +
    np.trapz(y, x=x, axis=1)  # integrate along axis 1
    +np.interp(x, xp, yp)      # interpolate function xp, yp at points x

    fft

    -
    np.fft.fft(y)             # complex fourier transform of y
    -np.fft.fftfreqs(len(y))   # fft frequencies for a given length
    +
    np.fft.fft(y)             # complex fourier transform of y
    +np.fft.fftfreqs(len(y))   # fft frequencies for a given length
     np.fft.fftshift(freqs)    # shifts zero frequency to the middle
     np.fft.rfft(y)            # real fourier transform of y
    -np.fft.rfftfreqs(len(y))  # real fft frequencies for a given length
    +np.fft.rfftfreqs(len(y)) # real fft frequencies for a given length

    rounding

    -
    np.ceil(a)   # rounds to nearest upper int
    +
    np.ceil(a)   # rounds to nearest upper int
     np.floor(a)  # rounds to nearest lower int
    -np.round(a)  # rounds to neares int
    +np.round(a) # rounds to neares int

    random variables

    -
    np.random.normal(loc=0, scale=2, size=100)  # 100 normal distributed random numbers
    +
    np.random.normal(loc=0, scale=2, size=100)  # 100 normal distributed random numbers
     np.random.seed(23032)                       # resets the seed value
     np.random.rand(200)                         # 200 random numbers in [0, 1)
     np.random.uniform(1, 30, 200)               # 200 random numbers in [1, 30)
    -np.random.random_integers(1, 15, 300)       # 300 random integers between [1, 15]
    +np.random.random_integers(1, 15, 300) # 300 random integers between [1, 15]

    Matplotlib

    figures and axes

    -
    fig = plt.figure(figsize=(5, 2), facecolor='black')  # initialize figure
    -ax = fig.add_subplot(3, 2, 2)                        # add second subplot in a 3 x 2 grid
    -fig, axes = plt.subplots(5, 2, figsize=(5, 5))       # return fig and array of axes in a 5 x 2 grid
    -ax = fig.add_axes([left, bottom, width, height])     # manually add axes at a certain position
    +
    fig = plt.figure(figsize=(5, 2), facecolor='black')  # initialize figure
    +ax = fig.add_subplot(3, 2, 2)                        # add second subplot in a 3 x 2 grid
    +fig, axes = plt.subplots(5, 2, figsize=(5, 5))       # return fig and array of axes in a 5 x 2 grid
    +ax = fig.add_axes([left, bottom, width, height])     # manually add axes at a certain position

    figures and axes properties

    -
    fig.suptitle('title')            # big figure title
    -fig.subplots_adjust(bottom=0.1, right=0.8, top=0.9, wspace=0.2,
    -                    hspace=0.5)  # adjust subplot positions
    -fig.tight_layout(pad=0.1,h_pad=0.5, w_pad=0.5, rect=None) # adjust
    +
    fig.suptitle('title')            # big figure title
    +fig.subplots_adjust(bottom=0.1, right=0.8, top=0.9, wspace=0.2,
    +                    hspace=0.5)  # adjust subplot positions
    +fig.tight_layout(pad=0.1,h_pad=0.5, w_pad=0.5, rect=None) # adjust
     subplots to fit perfectly into fig
     ax.set_xlabel()                  # set xlabel
     ax.set_ylabel()                  # set ylabel
     ax.set_xlim(1, 2)                # sets x limits
     ax.set_ylim(3, 4)                # sets y limits
     ax.set_title('blabla')           # sets the axis title
    -ax.set(xlabel='bla')             # set multiple parameters at once
    -ax.legend(loc='upper center')    # activate legend
    -ax.grid(True, which='both')      # activate grid
    -bbox = ax.get_position()         # returns the axes bounding box
    -bbox.x0 + bbox.width             # bounding box parameters
    +ax.set(xlabel='bla') # set multiple parameters at once +ax.legend(loc='upper center') # activate legend +ax.grid(True, which='both') # activate grid +bbox = ax.get_position() # returns the axes bounding box +bbox.x0 + bbox.width # bounding box parameters

    plotting routines

    -
    ax.plot(x,y, '-o', c='red', lw=2, label='bla')  # plots a line
    -ax.scatter(x,y, s=20, c=color)                  # scatter plot
    -ax.pcolormesh(xx,yy,zz, shading='gouraud')      # fast colormesh function
    -ax.colormesh(xx,yy,zz, norm=norm)               # slower colormesh function
    -ax.contour(xx,yy,zz, cmap='jet')                # contour line plot
    -ax.contourf(xx,yy,zz, vmin=2, vmax=4)           # filled contours plot
    -n, bins, patch = ax.hist(x, 50)                 # histogram
    -ax.imshow(matrix, origin='lower', extent=(x1, x2, y1, y2))  # show image
    -ax.specgram(y, FS=0.1, noverlap=128, scale='linear')  # plot a spectrogram
    +
    ax.plot(x,y, '-o', c='red', lw=2, label='bla')  # plots a line
    +ax.scatter(x,y, s=20, c=color)                  # scatter plot
    +ax.pcolormesh(xx,yy,zz, shading='gouraud')      # fast colormesh function
    +ax.colormesh(xx,yy,zz, norm=norm)               # slower colormesh function
    +ax.contour(xx,yy,zz, cmap='jet')                # contour line plot
    +ax.contourf(xx,yy,zz, vmin=2, vmax=4)           # filled contours plot
    +n, bins, patch = ax.hist(x, 50)                 # histogram
    +ax.imshow(matrix, origin='lower', extent=(x1, x2, y1, y2))  # show image
    +ax.specgram(y, FS=0.1, noverlap=128, scale='linear')  # plot a spectrogram
    diff --git a/stylesheets/normalize.css b/normalize.css similarity index 100% rename from stylesheets/normalize.css rename to normalize.css diff --git a/stylesheets/stylesheet.css b/stylesheet.css similarity index 100% rename from stylesheets/stylesheet.css rename to stylesheet.css From bc5d0fc9aae436efed15d0bf38a3c0f77dbe9845 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Tue, 26 Apr 2016 08:29:20 +0000 Subject: [PATCH 26/96] rebuild pages at a3343a7 --- github-light.css => stylesheets/github-light.css | 0 normalize.css => stylesheets/normalize.css | 0 stylesheet.css => stylesheets/stylesheet.css | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename github-light.css => stylesheets/github-light.css (100%) rename normalize.css => stylesheets/normalize.css (100%) rename stylesheet.css => stylesheets/stylesheet.css (100%) diff --git a/github-light.css b/stylesheets/github-light.css similarity index 100% rename from github-light.css rename to stylesheets/github-light.css diff --git a/normalize.css b/stylesheets/normalize.css similarity index 100% rename from normalize.css rename to stylesheets/normalize.css diff --git a/stylesheet.css b/stylesheets/stylesheet.css similarity index 100% rename from stylesheet.css rename to stylesheets/stylesheet.css From a61d089e726ba244237250c30a9bbe8084942ba2 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Thu, 28 Apr 2016 12:01:02 +0000 Subject: [PATCH 27/96] rebuild pages at 95d719e --- index.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/index.html b/index.html index d8d944f..a1e2ff0 100644 --- a/index.html +++ b/index.html @@ -213,7 +213,7 @@

    Functions, Classes, Generators, my_func()

    -

    NumPy

    +

    NumPy (import numpy as np)

    array initialization

    np.array([2, 3, 4])             # direct initialization
     np.empty(20, dtype=np.float32)  # single precision array with 20 entries
    @@ -302,7 +302,7 @@ 

    random variables

    np.random.random_integers(1, 15, 300) # 300 random integers between [1, 15]
    -

    Matplotlib

    +

    Matplotlib (import matplotlib.pyplot as plt)

    figures and axes

    fig = plt.figure(figsize=(5, 2), facecolor='black')  # initialize figure
     ax = fig.add_subplot(3, 2, 2)                        # add second subplot in a 3 x 2 grid
    
    From f573683985963480f716fc97195d9ad01053e304 Mon Sep 17 00:00:00 2001
    From: Thomas Belahi 
    Date: Mon, 2 May 2016 08:25:31 +0000
    Subject: [PATCH 28/96] rebuild pages at 9def6a8
    
    ---
     index.html | 1 +
     1 file changed, 1 insertion(+)
    
    diff --git a/index.html b/index.html
    index a1e2ff0..04f510a 100644
    --- a/index.html
    +++ b/index.html
    @@ -264,6 +264,7 @@ 

    elementwise operations and ma a + b # addition with array b a / b # division with b (np.NaN for division by zero) np.exp(a) # exponential (complex and real) +np.power(a,b) # a to the power b np.sin(a) # sine np.cos(a) # cosine np.arctan2(y,x) # arctan(y/x) From d615c45a4777e8d72fd518c85b4e252df597ee6b Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 9 May 2016 10:13:44 +0000 Subject: [PATCH 29/96] rebuild pages at 170643c --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index 04f510a..0765a0c 100644 --- a/index.html +++ b/index.html @@ -279,7 +279,7 @@

    inner / outer products

    np.sum(a, axis=1) # sum over axis 1 np.abs(a) # return array with absolute values a[None, :] + b[:, None] # outer sum -a[None, :] * b[None, :] # outer product +a[None, :] * b[:, None] # outer product np.outer(a, b) # outer product np.sum(a * a.T) # matrix norm

    interpolation, integration

    From 976140aa000e111de46f92304796adbc463f4951 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Wed, 11 May 2016 12:50:47 +0000 Subject: [PATCH 30/96] rebuild pages at 148ad5b --- index.html | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/index.html b/index.html index 0765a0c..8fd2115 100644 --- a/index.html +++ b/index.html @@ -65,6 +65,11 @@

    Scientific Python Cheatsheet

  • Control Flow
  • Functions, Classes, Generators, Decorators
  • +
  • IPython +
      +
    • [Python Console]
    • +
    • [Debugger commands]
    • +
  • NumPy
  • +

    IPython

    +

    Python console

    +
    <object>?  # Information about the object
    +<object>.<TAB>  # tab completion
    +
    +# measure runtime of a function:
    +%timeit range(1000)
    +100000 loops, best of 3: 7.76 us per loop
    +
    +# run scripts and debug
    +%run
    +%run -d  # run in debug mode
    +%run -t  # measures execution time
    +%run -p  # runs a profiler
    +%debug  # jumps to the debugger after an exception
    +
    +%pdb  # run debugger automatically on exception
    +
    +# examine history
    +%history
    +%history ~1/1-5  # lines 1-5 of last session
    +
    +# run shell commands
    +!make  # prefix command with "!"
    +
    +# clean namespace
    +%reset
    +

    Debugger commands

    +
    n  # execute next line
    +
    +

    NumPy (import numpy as np)

    array initialization

    np.array([2, 3, 4])             # direct initialization
    
    From 67749697e6c79e6061a99ac48bb10d61d0dd9072 Mon Sep 17 00:00:00 2001
    From: Thomas Belahi 
    Date: Wed, 11 May 2016 13:13:44 +0000
    Subject: [PATCH 31/96] rebuild pages at b407eec
    
    ---
     index.html | 4 ++--
     1 file changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/index.html b/index.html
    index 8fd2115..7ac1320 100644
    --- a/index.html
    +++ b/index.html
    @@ -67,8 +67,8 @@ 

    Scientific Python Cheatsheet

  • IPython
  • NumPy
      From 288ab0b92eb954d254ab7547f56350a0e8cc2ce7 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Thu, 9 Jun 2016 16:11:43 +0000 Subject: [PATCH 32/96] rebuild pages at eedc74b --- index.html | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/index.html b/index.html index 7ac1320..6043ff5 100644 --- a/index.html +++ b/index.html @@ -382,5 +382,16 @@

      plotting routines

      + + From 9eb291b121ea83cf8aed4a34e0f37616b1f6958a Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Fri, 10 Jun 2016 09:09:21 +0000 Subject: [PATCH 33/96] rebuild pages at bd7b48b --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index 6043ff5..6736e76 100644 --- a/index.html +++ b/index.html @@ -215,7 +215,7 @@

      Functions, Classes, Generators, def my_funct(): print 'func' -my_func()

  • +my_funct()

    IPython

    From 5abdf8c9c6d777d5e2fbb272b9902b714567d408 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Fri, 10 Jun 2016 09:14:07 +0000 Subject: [PATCH 34/96] rebuild pages at a86f47a --- index.html | 2 ++ 1 file changed, 2 insertions(+) diff --git a/index.html b/index.html index 6736e76..ba4c77d 100644 --- a/index.html +++ b/index.html @@ -48,6 +48,8 @@ + Fork me on GitHub +
    From 739ed218b6c397121a9b79965551cbb1bae75539 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Fri, 10 Jun 2016 09:25:21 +0000 Subject: [PATCH 35/96] rebuild pages at 1dfa200 --- index.html | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/index.html b/index.html index ba4c77d..08fa9f3 100644 --- a/index.html +++ b/index.html @@ -203,7 +203,8 @@

    Functions, Classes, Generators, yield num num += 1 -x = [for i in firstn(10)] +# consume the generator with list comprehension +x = [i for i in firstn(10)] # Decorators class myDecorator(object): From bac37a593ea84373e0e409380dbb941f4e828f59 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Fri, 10 Jun 2016 13:28:18 +0000 Subject: [PATCH 36/96] rebuild pages at 8e177c8 --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index 08fa9f3..0b301ca 100644 --- a/index.html +++ b/index.html @@ -185,7 +185,7 @@

    Functions, Classes, Generators, def myfunc(a1, a2): return x -x = my_function(a1,a2) +x = myfunc(a1, a2) # Class class Point(object): From 1bdc241a84867b5e34e76eff051ac38e1f3bf310 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Fri, 10 Jun 2016 14:22:25 +0000 Subject: [PATCH 37/96] rebuild pages at 18ac0f1 --- index.html | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/index.html b/index.html index 0b301ca..b05187c 100644 --- a/index.html +++ b/index.html @@ -249,7 +249,17 @@

    Python console

    # clean namespace %reset

    Debugger commands

    -
    n  # execute next line
    +
    n  # execute next line
    +b 42  # set breakpoint in the main file at line 42
    +b myfile.py:42  # set breakpoint in 'myfile.py' at line 42
    +c  # continue execution
    +l  # show current position in the code
    +p data  # print the 'data' variable
    +pp data  # pretty print the 'data' variable
    +s  # step into subroutine
    +a  # print arguments that a function received
    +pp locals()  # show all variables in local scope
    +pp globals()  # show all variables in global scope

    NumPy (import numpy as np)

    From bbc4d6d0dd5703655a5fe775698d17da24a047f7 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Fri, 10 Jun 2016 14:23:07 +0000 Subject: [PATCH 38/96] rebuild pages at 4d40e72 --- index.html | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/index.html b/index.html index b05187c..3936704 100644 --- a/index.html +++ b/index.html @@ -249,17 +249,17 @@

    Python console

    # clean namespace %reset

    Debugger commands

    -
    n  # execute next line
    -b 42  # set breakpoint in the main file at line 42
    +
    n               # execute next line
    +b 42            # set breakpoint in the main file at line 42
     b myfile.py:42  # set breakpoint in 'myfile.py' at line 42
    -c  # continue execution
    -l  # show current position in the code
    -p data  # print the 'data' variable
    -pp data  # pretty print the 'data' variable
    -s  # step into subroutine
    -a  # print arguments that a function received
    -pp locals()  # show all variables in local scope
    -pp globals()  # show all variables in global scope
    +c # continue execution +l # show current position in the code +p data # print the 'data' variable +pp data # pretty print the 'data' variable +s # step into subroutine +a # print arguments that a function received +pp locals() # show all variables in local scope +pp globals() # show all variables in global scope

    NumPy (import numpy as np)

    From 3aaabc39a6dc4eb00a3dc04fb9b3cf0bbcd84bbf Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Fri, 10 Jun 2016 15:07:57 +0000 Subject: [PATCH 39/96] rebuild pages at d181bf2 --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index 3936704..fa9ff08 100644 --- a/index.html +++ b/index.html @@ -119,7 +119,7 @@

    Lists

    Dictionaries

    a = {'red': 'rouge', 'blue': 'bleu', 'green': 'vert'}  # dictionary
     b = a['red']                                           # translate item
    -c = [value for key, value in b.items()]                # loop through contents
    +c = [value for key, value in a.items()]                # loop through contents
     d = a.get('yellow', 'no translation found')            # return default

    Strings

    a = 'red'                      # assignment
    
    From f4caa79b92846118433a7670abd1ffa4be43811b Mon Sep 17 00:00:00 2001
    From: Thomas Belahi 
    Date: Fri, 10 Jun 2016 15:22:40 +0000
    Subject: [PATCH 40/96] rebuild pages at 52e6cca
    
    ---
     index.html | 1 +
     1 file changed, 1 insertion(+)
    
    diff --git a/index.html b/index.html
    index fa9ff08..98719d2 100644
    --- a/index.html
    +++ b/index.html
    @@ -3,6 +3,7 @@
     
       
         
    +    
         Scientific python cheat sheet by IPGP
         
         
    
    From 16f2cf5609a7eb6e5aff08ec78d206ae0da27e61 Mon Sep 17 00:00:00 2001
    From: Thomas Belahi 
    Date: Fri, 10 Jun 2016 19:23:46 +0000
    Subject: [PATCH 41/96] rebuild pages at d2dfae5
    
    ---
     index.html | 22 +++++++++++-----------
     1 file changed, 11 insertions(+), 11 deletions(-)
    
    diff --git a/index.html b/index.html
    index 98719d2..103ac60 100644
    --- a/index.html
    +++ b/index.html
    @@ -106,7 +106,7 @@ 

    Types

    f = 'word' # string

    Lists

    a = ['red', 'blue', 'green']      # manually initialization
    -b = range(5)                      # initialization through a function
    +b = list(range(5))                # initialization through a function
     c = [nu**2 for nu in b]           # initialize through list comprehension
     d = [nu**2 for nu in b if b < 3]  # list comprehension withcondition
     e = c[0]                          # access element
    @@ -151,27 +151,27 @@ 

    Control Flow

    # if/elif/else
     a, b = 1, 2
     if a + b == 3:
    -    print 'True'
    +    print('True')
     elif a + b == 1:
    -    print 'False'
    +    print('False')
     else:
    -    print '?'
    +    print('?')
     
     # for
     a = ['red', 'blue', 'green']
     for color in a:
    -    print color
    +    print(color)
     
     # while
     number = 1
     while number < 10:
    -    print number
    +    print(number)
         number += 1
     
     # break
     number = 1
     while True:
    -    print number
    +    print(number)
         number += 1
         if number > 10:
             break
    @@ -180,7 +180,7 @@ 

    Control Flow

    for i in range(20): if i % 2 == 0: continue - print i
    + print(i)

    Functions, Classes, Generators, Decorators

    # Function
     def myfunc(a1, a2):
    @@ -193,7 +193,7 @@ 

    Functions, Classes, Generators, def __init__(self, x): self.x = x def __call__(self): - print self.x + print(self.x) x = Point(3) @@ -212,12 +212,12 @@

    Functions, Classes, Generators, def __init__(self, f): self.f = f def __call__(self): - print "call" + print("call") self.f() @myDecorator def my_funct(): - print 'func' + print('func') my_funct()

    From 95c3c900e9c066adadd642a816cc03a355d22d09 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Fri, 10 Jun 2016 23:57:06 +0000 Subject: [PATCH 42/96] rebuild pages at 491dcd9 --- index.html | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/index.html b/index.html index 103ac60..3f6b1ee 100644 --- a/index.html +++ b/index.html @@ -303,11 +303,10 @@

    indexing

    np.transpose(a, (2, 1, 0)) # transpose array to new axis order a[a < 2] # returns array that fulfills elementwise condition

    boolean arrays

    -
    a < 2                          # returns array with boolean values
    -np.logical_and(a < 2, b > 10)  # elementwise logical and
    -np.logical_or(a < 2, b > 10)   # elementwise logical or
    -~a                             # invert boolean array
    -np.invert(a)                   # invert boolean array
    +
    a < 2                         # returns array with boolean values
    +(a < 2) & (b > 10)            # elementwise logical and
    +(a < 2) | (b > 10)            # elementwise logical or
    +~a                            # invert boolean array

    elementwise operations and math functions

    a * 5              # multiplication with scalar
     a + 5              # addition with scalar
    
    From 9eab860122bcbbe860949820ae3760d544cd36c5 Mon Sep 17 00:00:00 2001
    From: Thomas Belahi 
    Date: Sat, 11 Jun 2016 09:07:46 +0000
    Subject: [PATCH 43/96] rebuild pages at 5816a7a
    
    ---
     index.html | 45 +++++++++++++++++++++++----------------------
     1 file changed, 23 insertions(+), 22 deletions(-)
    
    diff --git a/index.html b/index.html
    index 3f6b1ee..36bf0b5 100644
    --- a/index.html
    +++ b/index.html
    @@ -105,18 +105,18 @@ 

    Types

    e = 4 > 5 # boolean f = 'word' # string

    Lists

    -
    a = ['red', 'blue', 'green']      # manually initialization
    -b = list(range(5))                # initialization through a function
    -c = [nu**2 for nu in b]           # initialize through list comprehension
    -d = [nu**2 for nu in b if b < 3]  # list comprehension withcondition
    -e = c[0]                          # access element
    -f = e[1: 2]                       # access a slice of the list
    -g = ['re', 'bl'] + ['gr']         # list concatenation
    -h = ['re'] * 5                    # repeat a list
    -['re', 'bl'].index('re')          # returns index of 're'
    -'re' in ['re', 'bl']              # true if 're' in list
    -sorted([3, 2, 1])                 # returns sorted list
    -z = ['red'] + ['green', 'blue']   # list concatenation
    +
    a = ['red', 'blue', 'green']       # manually initialization
    +b = list(range(5))                 # initialization through a function
    +c = [nu**2 for nu in b]            # initialize through list comprehension
    +d = [nu**2 for nu in b if nu < 3]  # list comprehension with condition
    +e = c[0]                           # access element
    +f = e[1:2]                         # access a slice of the list
    +g = ['re', 'bl'] + ['gr']          # list concatenation
    +h = ['re'] * 5                     # repeat a list
    +['re', 'bl'].index('re')           # returns index of 're'
    +'re' in ['re', 'bl']               # true if 're' in list
    +sorted([3, 2, 1])                  # returns sorted list
    +z = ['red'] + ['green', 'blue']    # list concatenation

    Dictionaries

    a = {'red': 'rouge', 'blue': 'bleu', 'green': 'vert'}  # dictionary
     b = a['red']                                           # translate item
    @@ -184,7 +184,7 @@ 

    Control Flow

    Functions, Classes, Generators, Decorators

    # Function
     def myfunc(a1, a2):
    -    return x
    +    return a1 + a2
     
     x = myfunc(a1, a2)
     
    @@ -293,8 +293,8 @@ 

    array properties and operations

    np.argsort(a, axis=1) # return sorted index array along axis

    indexing

    a = np.arange(100)          # initialization with 0 - 99
    -a[: 3] = 0                  # set the first three indices to zero
    -a[1: 5] = 1                 # set indices 1-4 to 1
    +a[:3] = 0                   # set the first three indices to zero
    +a[1:5] = 1                  # set indices 1-4 to 1
     a[start:stop:step]          # general form of indexing/slicing
     a[None, :]                  # transform to column vector
     a[[1, 1, 3, 8]]             # return array with values of the indices
    @@ -362,8 +362,8 @@ 

    figures and axes properties

    fig.suptitle('title')            # big figure title
     fig.subplots_adjust(bottom=0.1, right=0.8, top=0.9, wspace=0.2,
                         hspace=0.5)  # adjust subplot positions
    -fig.tight_layout(pad=0.1,h_pad=0.5, w_pad=0.5, rect=None) # adjust
    -subplots to fit perfectly into fig
    +fig.tight_layout(pad=0.1, h_pad=0.5, w_pad=0.5,
    +                 rect=None)      # adjust subplots to fit perfectly into fig
     ax.set_xlabel()                  # set xlabel
     ax.set_ylabel()                  # set ylabel
     ax.set_xlim(1, 2)                # sets x limits
    @@ -377,12 +377,13 @@ 

    figures and axes properties

    plotting routines

    ax.plot(x,y, '-o', c='red', lw=2, label='bla')  # plots a line
     ax.scatter(x,y, s=20, c=color)                  # scatter plot
    -ax.pcolormesh(xx,yy,zz, shading='gouraud')      # fast colormesh function
    -ax.colormesh(xx,yy,zz, norm=norm)               # slower colormesh function
    -ax.contour(xx,yy,zz, cmap='jet')                # contour line plot
    -ax.contourf(xx,yy,zz, vmin=2, vmax=4)           # filled contours plot
    +ax.pcolormesh(xx, yy, zz, shading='gouraud')    # fast colormesh function
    +ax.colormesh(xx, yy, zz, norm=norm)             # slower colormesh function
    +ax.contour(xx, yy, zz, cmap='jet')              # contour line plot
    +ax.contourf(xx, yy, zz, vmin=2, vmax=4)         # filled contours plot
     n, bins, patch = ax.hist(x, 50)                 # histogram
    -ax.imshow(matrix, origin='lower', extent=(x1, x2, y1, y2))  # show image
    +ax.imshow(matrix, origin='lower',
    +          extent=(x1, x2, y1, y2))              # show image
     ax.specgram(y, FS=0.1, noverlap=128, scale='linear')  # plot a spectrogram
    From 5636575cdf5c8fc60453450dbbade458d6399b12 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Sat, 11 Jun 2016 20:03:21 +0000 Subject: [PATCH 44/96] rebuild pages at 2ffb258 --- index.html | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/index.html b/index.html index 36bf0b5..93a9492 100644 --- a/index.html +++ b/index.html @@ -115,8 +115,7 @@

    Lists

    h = ['re'] * 5 # repeat a list ['re', 'bl'].index('re') # returns index of 're' 're' in ['re', 'bl'] # true if 're' in list -sorted([3, 2, 1]) # returns sorted list -z = ['red'] + ['green', 'blue'] # list concatenation
    +sorted([3, 2, 1]) # returns sorted list

    Dictionaries

    a = {'red': 'rouge', 'blue': 'bleu', 'green': 'vert'}  # dictionary
     b = a['red']                                           # translate item
    
    From f767a5d4d7e85daa56e3b03516a1f0d9861c3081 Mon Sep 17 00:00:00 2001
    From: Thomas Belahi 
    Date: Sun, 12 Jun 2016 20:33:38 +0000
    Subject: [PATCH 45/96] rebuild pages at 1325177
    
    ---
     index.html | 58 +++++++++++++++++++++++++++---------------------------
     1 file changed, 29 insertions(+), 29 deletions(-)
    
    diff --git a/index.html b/index.html
    index 93a9492..8490483 100644
    --- a/index.html
    +++ b/index.html
    @@ -77,8 +77,8 @@ 

    Scientific Python Cheatsheet

    • array initialization
    • reading/ writing files
    • -
    • array properties and operations
    • indexing
    • +
    • array properties and operations
    • boolean arrays
    • elementwise operations and math functions
    • inner / outer products
    • @@ -110,7 +110,7 @@

      Lists

      c = [nu**2 for nu in b] # initialize through list comprehension d = [nu**2 for nu in b if nu < 3] # list comprehension with condition e = c[0] # access element -f = e[1:2] # access a slice of the list +f = c[1:2] # access a slice of the list g = ['re', 'bl'] + ['gr'] # list concatenation h = ['re'] * 5 # repeat a list ['re', 'bl'].index('re') # returns index of 're' @@ -136,7 +136,7 @@

      Operators

      3 * 2 # multiplication 3 ** 2 # exponent 3 % 2 # remainder -abs() # absolute value +abs(a) # absolute value 1 == 1 # equal 2 > 1 # larger 2 < 1 # smaller @@ -144,7 +144,7 @@

      Operators

      1 != 2 and 2 < 3 # logical AND 1 != 2 or 2 < 3 # logical OR not 1 == 2 # logical NOT -a in b # test if a is in b +'a' in b # test if a is in b a is b # test if objects point to the same memory (id)

    Control Flow

    # if/elif/else
    @@ -277,6 +277,17 @@ 

    array initialization

    reading/ writing files

    np.fromfile(fname/object, dtype=np.float32, count=5)  # read binary data from file
     np.loadtxt(fname/object, skiprows=2, delimiter=',')   # read ascii data from file
    +

    indexing

    +
    a = np.arange(100)          # initialization with 0 - 99
    +a[:3] = 0                   # set the first three indices to zero
    +a[2:5] = 1                  # set indices 2-4 to 1
    +a[start:stop:step]          # general form of indexing/slicing
    +a[None, :]                  # transform to column vector
    +a[[1, 1, 3, 8]]             # return array with values of the indices
    +a = a.reshape(10, 10)       # transform to 10 x 10 matrix
    +a.T                         # return transposed view
    +b = np.transpose(a, (1, 0)) # transpose array to new axis order
    +a[a < 2]                    # returns array that fulfills elementwise condition

    array properties and operations

    a.shape                # a tuple with the lengths of each axis
     len(a)                 # length of axis 0
    @@ -285,22 +296,11 @@ 

    array properties and operations

    a.flatten() # collapse array to one dimension a.conj() # return complex conjugate a.astype(np.int16) # cast to integer -np.argmax(a, axis=2) # return index of maximum along a given axis +np.argmax(a, axis=1) # return index of maximum along a given axis np.cumsum(a) # return cumulative sum np.any(a) # True if any element is True np.all(a) # True if all elements are True np.argsort(a, axis=1) # return sorted index array along axis
    -

    indexing

    -
    a = np.arange(100)          # initialization with 0 - 99
    -a[:3] = 0                   # set the first three indices to zero
    -a[1:5] = 1                  # set indices 1-4 to 1
    -a[start:stop:step]          # general form of indexing/slicing
    -a[None, :]                  # transform to column vector
    -a[[1, 1, 3, 8]]             # return array with values of the indices
    -a = a.reshape(10, 10)       # transform to 10 x 10 matrix
    -a.T                         # return transposed view
    -np.transpose(a, (2, 1, 0))  # transpose array to new axis order
    -a[a < 2]                    # returns array that fulfills elementwise condition

    boolean arrays

    a < 2                         # returns array with boolean values
     (a < 2) & (b > 10)            # elementwise logical and
    @@ -312,18 +312,18 @@ 

    elementwise operations and ma a + b # addition with array b a / b # division with b (np.NaN for division by zero) np.exp(a) # exponential (complex and real) -np.power(a,b) # a to the power b +np.power(a, b) # a to the power b np.sin(a) # sine np.cos(a) # cosine -np.arctan2(y,x) # arctan(y/x) -np.arcsin(x) # arcsin +np.arctan2(a, b) # arctan(a/b) +np.arcsin(a) # arcsin np.radians(a) # degrees to radians np.degrees(a) # radians to degrees np.var(a) # variance of array np.std(a, axis=1) # standard deviation

    inner / outer products

    np.dot(a, b)                        # inner matrix product: a_mi b_in
    -np.einsum('ijkl,klmn->ijmn', a, b)  # einstein summation convention
    +np.einsum('ij,kj->ik', a, b)        # einstein summation convention
     np.sum(a, axis=1)                   # sum over axis 1
     np.abs(a)                           # return array with absolute values
     a[None, :] + b[:, None]             # outer sum
    @@ -331,14 +331,14 @@ 

    inner / outer products

    np.outer(a, b) # outer product np.sum(a * a.T) # matrix norm

    interpolation, integration

    -
    np.trapz(y, x=x, axis=1)  # integrate along axis 1
    +
    np.trapz(a, x=x, axis=1)  # integrate along axis 1
     np.interp(x, xp, yp)      # interpolate function xp, yp at points x

    fft

    -
    np.fft.fft(y)             # complex fourier transform of y
    -np.fft.fftfreqs(len(y))   # fft frequencies for a given length
    -np.fft.fftshift(freqs)    # shifts zero frequency to the middle
    -np.fft.rfft(y)            # real fourier transform of y
    -np.fft.rfftfreqs(len(y))  # real fft frequencies for a given length
    +
    np.fft.fft(a)                # complex fourier transform of a
    +f = np.fft.fftfreq(len(a))   # fft frequencies for a given length
    +np.fft.fftshift(f)           # shifts zero frequency to the middle
    +np.fft.rfft(a)               # real fourier transform of a
    +np.fft.rfftfreq(len(a))      # real fft frequencies for a given length

    rounding

    np.ceil(a)   # rounds to nearest upper int
     np.floor(a)  # rounds to nearest lower int
    @@ -348,7 +348,7 @@ 

    random variables

    np.random.seed(23032) # resets the seed value np.random.rand(200) # 200 random numbers in [0, 1) np.random.uniform(1, 30, 200) # 200 random numbers in [1, 30) -np.random.random_integers(1, 15, 300) # 300 random integers between [1, 15]
    +np.random.randint(1, 16, 300) # 300 random integers between [1, 16)

    Matplotlib (import matplotlib.pyplot as plt)

    @@ -363,8 +363,8 @@

    figures and axes properties

    hspace=0.5) # adjust subplot positions fig.tight_layout(pad=0.1, h_pad=0.5, w_pad=0.5, rect=None) # adjust subplots to fit perfectly into fig -ax.set_xlabel() # set xlabel -ax.set_ylabel() # set ylabel +ax.set_xlabel('xbla') # set xlabel +ax.set_ylabel('ybla') # set ylabel ax.set_xlim(1, 2) # sets x limits ax.set_ylim(3, 4) # sets y limits ax.set_title('blabla') # sets the axis title From f8f3962b3b6c351f47c9bafda075cbee96cdc19b Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 13 Jun 2016 09:48:14 +0000 Subject: [PATCH 46/96] rebuild pages at 58dd226 --- index.html | 61 ++++++++++++++++++++++++++++++++++---- stylesheets/stylesheet.css | 19 +++++++++--- 2 files changed, 71 insertions(+), 9 deletions(-) diff --git a/index.html b/index.html index 8490483..4502a4c 100644 --- a/index.html +++ b/index.html @@ -55,6 +55,7 @@

    Scientific Python Cheatsheet

    +
    -
    +
    +

    Pure Python

    +
    +

    Types

    a = 2           # integer
     b = 5.0         # float
    @@ -104,6 +108,8 @@ 

    Types

    d = 1.5 + 0.5j # complex e = 4 > 5 # boolean f = 'word' # string
    +
    +

    Lists

    a = ['red', 'blue', 'green']       # manually initialization
     b = list(range(5))                 # initialization through a function
    @@ -116,17 +122,23 @@ 

    Lists

    ['re', 'bl'].index('re') # returns index of 're' 're' in ['re', 'bl'] # true if 're' in list sorted([3, 2, 1]) # returns sorted list
    +
    +

    Dictionaries

    a = {'red': 'rouge', 'blue': 'bleu', 'green': 'vert'}  # dictionary
     b = a['red']                                           # translate item
     c = [value for key, value in a.items()]                # loop through contents
     d = a.get('yellow', 'no translation found')            # return default
    +
    +

    Strings

    a = 'red'                      # assignment
     char = a[2]                    # access individual characters
     'red ' + 'blue'                # string concatenation
     '1, 2, three'.split(',')       # split string into list
     '.'.join(['1', '2', 'three'])  # concatenate list into string
    +
    +

    Operators

    a = 2             # assignment
     a += 1 (*=, /=)   # change and assign
    @@ -146,6 +158,8 @@ 

    Operators

    not 1 == 2 # logical NOT 'a' in b # test if a is in b a is b # test if objects point to the same memory (id)
    +
    +

    Control Flow

    # if/elif/else
     a, b = 1, 2
    @@ -180,6 +194,8 @@ 

    Control Flow

    if i % 2 == 0: continue print(i)
    +
    +

    Functions, Classes, Generators, Decorators

    # Function
     def myfunc(a1, a2):
    @@ -220,8 +236,11 @@ 

    Functions, Classes, Generators, my_funct()

    -
    +
    +

    IPython

    +
    +

    Python console

    <object>?  # Information about the object
     <object>.<TAB>  # tab completion
    @@ -248,6 +267,8 @@ 

    Python console

    # clean namespace %reset
    +
    +

    Debugger commands

    n               # execute next line
     b 42            # set breakpoint in the main file at line 42
    @@ -261,8 +282,11 @@ 

    Debugger commands

    pp locals() # show all variables in local scope pp globals() # show all variables in global scope
    -
    +
    +

    NumPy (import numpy as np)

    +
    +

    array initialization

    np.array([2, 3, 4])             # direct initialization
     np.empty(20, dtype=np.float32)  # single precision array with 20 entries
    @@ -274,9 +298,13 @@ 

    array initialization

    np.arange(0, 100, 2) # points from 0 to <100 with step width 2 np.logspace(-5, 2, 100) # 100 log-spaced points between 1e-5 and 1e2 np.copy(a) # copy array to new memory
    +
    +

    reading/ writing files

    np.fromfile(fname/object, dtype=np.float32, count=5)  # read binary data from file
     np.loadtxt(fname/object, skiprows=2, delimiter=',')   # read ascii data from file
    +
    +

    indexing

    a = np.arange(100)          # initialization with 0 - 99
     a[:3] = 0                   # set the first three indices to zero
    @@ -288,6 +316,8 @@ 

    indexing

    a.T # return transposed view b = np.transpose(a, (1, 0)) # transpose array to new axis order a[a < 2] # returns array that fulfills elementwise condition
    +
    +

    array properties and operations

    a.shape                # a tuple with the lengths of each axis
     len(a)                 # length of axis 0
    @@ -301,11 +331,15 @@ 

    array properties and operations

    np.any(a) # True if any element is True np.all(a) # True if all elements are True np.argsort(a, axis=1) # return sorted index array along axis
    +
    +

    boolean arrays

    a < 2                         # returns array with boolean values
     (a < 2) & (b > 10)            # elementwise logical and
     (a < 2) | (b > 10)            # elementwise logical or
     ~a                            # invert boolean array
    +
    +

    elementwise operations and math functions

    a * 5              # multiplication with scalar
     a + 5              # addition with scalar
    @@ -321,6 +355,8 @@ 

    elementwise operations and ma np.degrees(a) # radians to degrees np.var(a) # variance of array np.std(a, axis=1) # standard deviation

    +
    +

    inner / outer products

    np.dot(a, b)                        # inner matrix product: a_mi b_in
     np.einsum('ij,kj->ik', a, b)        # einstein summation convention
    @@ -330,19 +366,27 @@ 

    inner / outer products

    a[None, :] * b[:, None] # outer product np.outer(a, b) # outer product np.sum(a * a.T) # matrix norm
    +
    +

    interpolation, integration

    np.trapz(a, x=x, axis=1)  # integrate along axis 1
     np.interp(x, xp, yp)      # interpolate function xp, yp at points x
    +
    +

    fft

    np.fft.fft(a)                # complex fourier transform of a
     f = np.fft.fftfreq(len(a))   # fft frequencies for a given length
     np.fft.fftshift(f)           # shifts zero frequency to the middle
     np.fft.rfft(a)               # real fourier transform of a
     np.fft.rfftfreq(len(a))      # real fft frequencies for a given length
    +
    +

    rounding

    np.ceil(a)   # rounds to nearest upper int
     np.floor(a)  # rounds to nearest lower int
     np.round(a)  # rounds to neares int
    +
    +

    random variables

    np.random.normal(loc=0, scale=2, size=100)  # 100 normal distributed random numbers
     np.random.seed(23032)                       # resets the seed value
    @@ -350,13 +394,18 @@ 

    random variables

    np.random.uniform(1, 30, 200) # 200 random numbers in [1, 30) np.random.randint(1, 16, 300) # 300 random integers between [1, 16)
    -
    +
    +

    Matplotlib (import matplotlib.pyplot as plt)

    +
    +

    figures and axes

    fig = plt.figure(figsize=(5, 2), facecolor='black')  # initialize figure
     ax = fig.add_subplot(3, 2, 2)                        # add second subplot in a 3 x 2 grid
     fig, axes = plt.subplots(5, 2, figsize=(5, 5))       # return fig and array of axes in a 5 x 2 grid
     ax = fig.add_axes([left, bottom, width, height])     # manually add axes at a certain position
    +
    +

    figures and axes properties

    fig.suptitle('title')            # big figure title
     fig.subplots_adjust(bottom=0.1, right=0.8, top=0.9, wspace=0.2,
    @@ -373,6 +422,8 @@ 

    figures and axes properties

    ax.grid(True, which='both') # activate grid bbox = ax.get_position() # returns the axes bounding box bbox.x0 + bbox.width # bounding box parameters
    +
    +

    plotting routines

    ax.plot(x,y, '-o', c='red', lw=2, label='bla')  # plots a line
     ax.scatter(x,y, s=20, c=color)                  # scatter plot
    @@ -385,7 +436,7 @@ 

    plotting routines

    extent=(x1, x2, y1, y2)) # show image ax.specgram(y, FS=0.1, noverlap=128, scale='linear') # plot a spectrogram
    -
    +
    Scientific python cheat sheet is maintained by IPGP. diff --git a/stylesheets/stylesheet.css b/stylesheets/stylesheet.css index 134c774..1ffd8ef 100644 --- a/stylesheets/stylesheet.css +++ b/stylesheets/stylesheet.css @@ -109,16 +109,27 @@ a { -moz-column-count:auto; -webkit-column-count: auto; - -webkit-column-width: 330px; - -moz-column-width: 330px; - column-width: 330px; - box-sizing: unset;} .main-content .group { display: inline-block; + -webkit-column-width: 500px; + -moz-column-width: 500px; + column-width: 500px; + + border-radius: 25px; + border-size:2px; + border-style:solid; + border-color:#D8D8D8; + + padding: 10px; width: 100%;} +.main-content .subgroup{ + display: inline-block; + + width: 500px;} + .main-content :first-child { margin-top: 0; } From 0ea6381ad843c3f2196ab33472abbfa77ffcd381 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 13 Jun 2016 11:04:15 +0000 Subject: [PATCH 47/96] rebuild pages at 2f36a1c --- index.html | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/index.html b/index.html index 4502a4c..04dd526 100644 --- a/index.html +++ b/index.html @@ -143,7 +143,7 @@

    Operators

    a = 2             # assignment
     a += 1 (*=, /=)   # change and assign
     3 + 2             # addition
    -3 / 2             # integer division (python2) or float division (python3)
    +3 / 2             # integer (python2) or float (python3) division
     3 // 2            # integer division
     3 * 2             # multiplication
     3 ** 2            # exponent
    @@ -301,8 +301,10 @@ 

    array initialization

    reading/ writing files

    -
    np.fromfile(fname/object, dtype=np.float32, count=5)  # read binary data from file
    -np.loadtxt(fname/object, skiprows=2, delimiter=',')   # read ascii data from file
    +
    np.fromfile(fname/fobject, dtype=np.float32, count=5)  # read binary data from file
    +np.loadtxt(fname/fobject, skiprows=2, delimiter=',')   # read ascii data from file
    +np.savetxt(fname/fobject, array, fmt='%.5f')           # write ascii data
    +np.tofile(fname/fobject)                               # write binary data (C-order)

    indexing

    From d2693cf02fe27086024ef75d97671868595e1acd Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 13 Jun 2016 12:38:37 +0000 Subject: [PATCH 48/96] rebuild pages at b44d6dd --- index.html | 37 +++++++++++++++++++++++++++++-------- 1 file changed, 29 insertions(+), 8 deletions(-) diff --git a/index.html b/index.html index 04dd526..ec31730 100644 --- a/index.html +++ b/index.html @@ -94,6 +94,11 @@

    Scientific Python Cheatsheet

  • figures and axes properties
  • plotting routines
  • +
  • Scipy +
  • @@ -402,10 +407,10 @@

    Matplotlib (import mat

    figures and axes

    -
    fig = plt.figure(figsize=(5, 2), facecolor='black')  # initialize figure
    -ax = fig.add_subplot(3, 2, 2)                        # add second subplot in a 3 x 2 grid
    -fig, axes = plt.subplots(5, 2, figsize=(5, 5))       # return fig and array of axes in a 5 x 2 grid
    -ax = fig.add_axes([left, bottom, width, height])     # manually add axes at a certain position
    +
    fig = plt.figure(figsize=(5, 2))                  # initialize figure
    +ax = fig.add_subplot(3, 2, 2)                     # add second subplot in a 3 x 2 grid
    +fig, axes = plt.subplots(5, 2, figsize=(5, 5))    # return fig and 5 x 2 array of axes
    +ax = fig.add_axes([left, bottom, width, height])  # add custom axis

    figures and axes properties

    @@ -413,7 +418,7 @@

    figures and axes properties

    fig.subplots_adjust(bottom=0.1, right=0.8, top=0.9, wspace=0.2, hspace=0.5) # adjust subplot positions fig.tight_layout(pad=0.1, h_pad=0.5, w_pad=0.5, - rect=None) # adjust subplots to fit perfectly into fig + rect=None) # adjust subplots to fit into fig ax.set_xlabel('xbla') # set xlabel ax.set_ylabel('ybla') # set ylabel ax.set_xlim(1, 2) # sets x limits @@ -429,14 +434,30 @@

    figures and axes properties

    plotting routines

    ax.plot(x,y, '-o', c='red', lw=2, label='bla')  # plots a line
     ax.scatter(x,y, s=20, c=color)                  # scatter plot
    -ax.pcolormesh(xx, yy, zz, shading='gouraud')    # fast colormesh function
    -ax.colormesh(xx, yy, zz, norm=norm)             # slower colormesh function
    +ax.pcolormesh(xx, yy, zz, shading='gouraud')    # fast colormesh
    +ax.colormesh(xx, yy, zz, norm=norm)             # slower colormesh
     ax.contour(xx, yy, zz, cmap='jet')              # contour line plot
     ax.contourf(xx, yy, zz, vmin=2, vmax=4)         # filled contours plot
     n, bins, patch = ax.hist(x, 50)                 # histogram
     ax.imshow(matrix, origin='lower',
               extent=(x1, x2, y1, y2))              # show image
    -ax.specgram(y, FS=0.1, noverlap=128, scale='linear')  # plot a spectrogram
    +ax.specgram(y, FS=0.1, noverlap=128, + scale='linear') # plot a spectrogram
    +
    +
    + +

    Scipy (import scipy as sci)

    +
    +
    +

    interpolation

    +
    from scipy.ndimage import map_coordinates       # interpolates a data
    +pts_new = map_coordinates(data, float_indices,  # array at index coordinate
    +                          order=3)              # positions
    +
    +
    +

    Integration

    +
    from scipy.integrate import quad
    +value = quad(func, low_lim, up_lim)  # definite integral of python function
    From 04def3fbc8c82d4c4bff4fceef6afa6407e13b95 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 13 Jun 2016 12:44:26 +0000 Subject: [PATCH 49/96] rebuild pages at 1fc28bc --- index.html | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/index.html b/index.html index ec31730..c54f07c 100644 --- a/index.html +++ b/index.html @@ -305,13 +305,6 @@

    array initialization

    np.copy(a) # copy array to new memory
    -

    reading/ writing files

    -
    np.fromfile(fname/fobject, dtype=np.float32, count=5)  # read binary data from file
    -np.loadtxt(fname/fobject, skiprows=2, delimiter=',')   # read ascii data from file
    -np.savetxt(fname/fobject, array, fmt='%.5f')           # write ascii data
    -np.tofile(fname/fobject)                               # write binary data (C-order)
    -
    -

    indexing

    a = np.arange(100)          # initialization with 0 - 99
     a[:3] = 0                   # set the first three indices to zero
    @@ -375,6 +368,13 @@ 

    inner / outer products

    np.sum(a * a.T) # matrix norm
    +

    reading/ writing files

    +
    np.fromfile(fname/fobject, dtype=np.float32, count=5)  # read binary data from file
    +np.loadtxt(fname/fobject, skiprows=2, delimiter=',')   # read ascii data from file
    +np.savetxt(fname/fobject, array, fmt='%.5f')           # write ascii data
    +np.tofile(fname/fobject)                               # write binary data (C-order)
    +
    +

    interpolation, integration

    np.trapz(a, x=x, axis=1)  # integrate along axis 1
     np.interp(x, xp, yp)      # interpolate function xp, yp at points x
    From 5594d446ca5c40e8b617a3caf953db34ec6d2b2f Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 13 Jun 2016 12:47:14 +0000 Subject: [PATCH 50/96] rebuild pages at ef6ee60 --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index c54f07c..65febae 100644 --- a/index.html +++ b/index.html @@ -77,12 +77,12 @@

    Scientific Python Cheatsheet

  • NumPy
  • +
    + +

    Pandas

    +
    +

    python import pandas as pd # import pandas df = pd.read_csv("filename.csv") # read and load CSV file in a DataFrame print(df[:2]) # print first 2 lines of the DataFrame raw = df.values # get raw data out of DataFrame object cols = df.columns # get list of columns headers

    From ece15a57ec959ef039280de236d5364d11d3fb50 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 13 Jun 2016 13:46:29 +0000 Subject: [PATCH 52/96] rebuild pages at 0b93249 --- index.html | 1 + 1 file changed, 1 insertion(+) diff --git a/index.html b/index.html index d8443fd..9e912ea 100644 --- a/index.html +++ b/index.html @@ -99,6 +99,7 @@

    Scientific Python Cheatsheet

  • interpolation
  • integration
  • +
  • Pandas
  • From 2c852937c722d9dadafda28cc0690643f03c09ad Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 13 Jun 2016 13:56:47 +0000 Subject: [PATCH 53/96] rebuild pages at 05dca72 --- index.html | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/index.html b/index.html index 9e912ea..7cd8a7e 100644 --- a/index.html +++ b/index.html @@ -99,7 +99,10 @@

    Scientific Python Cheatsheet

  • interpolation
  • integration
  • -
  • Pandas
  • +
  • Pandas +
  • @@ -464,7 +467,17 @@

    Integration

    Pandas

    -

    python import pandas as pd # import pandas df = pd.read_csv("filename.csv") # read and load CSV file in a DataFrame print(df[:2]) # print first 2 lines of the DataFrame raw = df.values # get raw data out of DataFrame object cols = df.columns # get list of columns headers

    +
    +

    Data structures

    +
    import pandas as pd                                     # import pandas
    +s = pd.Series(np.random.rand(1000), index=range(1000))  # series
    +index = pd.date_range("13/06/2016", periods=1000)       # time index
    +df = pd.DataFrame(np.zeros(1000, 3), index=index,
    +                    columns=["A", "B", "C"])            # DataFrame
    +
    +
    +

    DataFrame

    +

    python df = pd.read_csv("filename.csv") # read and load CSV file in a DataFrame print(df[:2]) # print first 2 lines of the DataFrame raw = df.values # get raw data out of DataFrame object cols = df.columns # get list of columns headers

    From 97ed94bdec4c59d385787f20865c5a23b50d2722 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 13 Jun 2016 14:00:29 +0000 Subject: [PATCH 54/96] rebuild pages at bf5abcf --- index.html | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/index.html b/index.html index 7cd8a7e..993a296 100644 --- a/index.html +++ b/index.html @@ -101,7 +101,8 @@

    Scientific Python Cheatsheet

  • Pandas
  • @@ -477,7 +478,10 @@

    Data structures

    DataFrame

    -

    python df = pd.read_csv("filename.csv") # read and load CSV file in a DataFrame print(df[:2]) # print first 2 lines of the DataFrame raw = df.values # get raw data out of DataFrame object cols = df.columns # get list of columns headers

    +
    df = pd.read_csv("filename.csv")           # read and load CSV file in a DataFrame
    +print(df[:2])                              # print first 2 lines of the DataFrame
    +raw = df.values                            # get raw data out of DataFrame object
    +cols = df.columns                          # get list of columns headers
    From 75b386bc9443f577e84eb1c51d1e566e0a83311a Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 13 Jun 2016 14:05:56 +0000 Subject: [PATCH 55/96] rebuild pages at 135e887 --- index.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/index.html b/index.html index 993a296..91a4c0f 100644 --- a/index.html +++ b/index.html @@ -101,8 +101,8 @@

    Scientific Python Cheatsheet

  • Pandas
  • From 0267846548a8bb0bad2bfd95cbfff385f38c3eeb Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 13 Jun 2016 14:26:26 +0000 Subject: [PATCH 56/96] rebuild pages at a2b0a6b --- index.html | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/index.html b/index.html index 91a4c0f..f59b93f 100644 --- a/index.html +++ b/index.html @@ -380,9 +380,10 @@

    reading/ writing files

    np.tofile(fname/fobject) # write binary data (C-order)
    -

    interpolation, integration

    +

    interpolation, integration, optimization

    np.trapz(a, x=x, axis=1)  # integrate along axis 1
    -np.interp(x, xp, yp)      # interpolate function xp, yp at points x
    +np.interp(x, xp, yp) # interpolate function xp, yp at points x +np.linalg.lstsq(a, b) # solve a x = b in least square sense

    fft

    From 63a59541aaf6705d855ed08441ef2366a72b467b Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 13 Jun 2016 14:29:41 +0000 Subject: [PATCH 57/96] rebuild pages at 71c0601 --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index f59b93f..926471a 100644 --- a/index.html +++ b/index.html @@ -83,7 +83,7 @@

    Scientific Python Cheatsheet

  • elementwise operations and math functions
  • inner / outer products
  • reading/ writing files
  • -
  • interpolation, integration
  • +
  • interpolation, integration, optimization
  • fft
  • rounding
  • random variables
  • From 4db89747e439ba39baae9420456d7b96190fb9ff Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 13 Jun 2016 15:13:17 +0000 Subject: [PATCH 58/96] rebuild pages at 18f3683 --- index.html | 84 +++++++++++++++++++------------------- stylesheets/stylesheet.css | 16 ++++---- 2 files changed, 51 insertions(+), 49 deletions(-) diff --git a/index.html b/index.html index 926471a..1c97a92 100644 --- a/index.html +++ b/index.html @@ -122,9 +122,9 @@

    Types

    Lists

    a = ['red', 'blue', 'green']       # manually initialization
    -b = list(range(5))                 # initialization through a function
    -c = [nu**2 for nu in b]            # initialize through list comprehension
    -d = [nu**2 for nu in b if nu < 3]  # list comprehension with condition
    +b = list(range(5))                 # initialize from iteratable
    +c = [nu**2 for nu in b]            # list comprehension
    +d = [nu**2 for nu in b if nu < 3]  # conditioned list comprehension
     e = c[0]                           # access element
     f = c[1:2]                         # access a slice of the list
     g = ['re', 'bl'] + ['gr']          # list concatenation
    @@ -135,10 +135,10 @@ 

    Lists

    Dictionaries

    -
    a = {'red': 'rouge', 'blue': 'bleu', 'green': 'vert'}  # dictionary
    -b = a['red']                                           # translate item
    -c = [value for key, value in a.items()]                # loop through contents
    -d = a.get('yellow', 'no translation found')            # return default
    +
    a = {'red': 'rouge', 'blue': 'bleu'}         # dictionary
    +b = a['red']                                 # translate item
    +c = [value for key, value in a.items()]      # loop through contents
    +d = a.get('yellow', 'no translation found')  # return default

    Strings

    @@ -299,14 +299,14 @@

    NumPy (import numpy as np)

    array initialization

    np.array([2, 3, 4])             # direct initialization
    -np.empty(20, dtype=np.float32)  # single precision array with 20 entries
    +np.empty(20, dtype=np.float32)  # single precision array of size 20
     np.zeros(200)                   # initialize 200 zeros
     np.ones((3,3), dtype=np.int32)  # 3 x 3 integer matrix with ones
     np.eye(200)                     # ones on the diagonal
    -np.zeros_like(a)                # returns array with zeros and the shape of a
    +np.zeros_like(a)                # array with zeros and the shape of a
     np.linspace(0., 10., 100)       # 100 points from 0 to 10
    -np.arange(0, 100, 2)            # points from 0 to <100 with step width 2
    -np.logspace(-5, 2, 100)         # 100 log-spaced points between 1e-5 and 1e2
    +np.arange(0, 100, 2)            # points from 0 to <100 with step 2
    +np.logspace(-5, 2, 100)         # 100 log-spaced from 1e-5 -> 1e2
     np.copy(a)                      # copy array to new memory
    @@ -320,7 +320,7 @@

    indexing

    a = a.reshape(10, 10) # transform to 10 x 10 matrix a.T # return transposed view b = np.transpose(a, (1, 0)) # transpose array to new axis order -a[a < 2] # returns array that fulfills elementwise condition
    +a[a < 2] # values with elementwise condition

    array properties and operations

    @@ -363,21 +363,22 @@

    elementwise operations and ma

    inner / outer products

    -
    np.dot(a, b)                        # inner matrix product: a_mi b_in
    -np.einsum('ij,kj->ik', a, b)        # einstein summation convention
    -np.sum(a, axis=1)                   # sum over axis 1
    -np.abs(a)                           # return array with absolute values
    -a[None, :] + b[:, None]             # outer sum
    -a[None, :] * b[:, None]             # outer product
    -np.outer(a, b)                      # outer product
    -np.sum(a * a.T)                     # matrix norm
    +
    np.dot(a, b)                  # inner product: a_mi b_in
    +np.einsum('ij,kj->ik', a, b)  # einstein summation convention
    +np.sum(a, axis=1)             # sum over axis 1
    +np.abs(a)                     # return absolute values
    +a[None, :] + b[:, None]       # outer sum
    +a[None, :] * b[:, None]       # outer product
    +np.outer(a, b)                # outer product
    +np.sum(a * a.T)               # matrix norm

    reading/ writing files

    -
    np.fromfile(fname/fobject, dtype=np.float32, count=5)  # read binary data from file
    -np.loadtxt(fname/fobject, skiprows=2, delimiter=',')   # read ascii data from file
    +
    
    +np.fromfile(fname/fobject, dtype=np.float32, count=5)  # binary data from file
    +np.loadtxt(fname/fobject, skiprows=2, delimiter=',')   # ascii data from file
     np.savetxt(fname/fobject, array, fmt='%.5f')           # write ascii data
    -np.tofile(fname/fobject)                               # write binary data (C-order)
    +np.tofile(fname/fobject) # write (C) binary data

    interpolation, integration, optimization

    @@ -388,10 +389,10 @@

    interpolation, integration, opti

    fft

    np.fft.fft(a)                # complex fourier transform of a
    -f = np.fft.fftfreq(len(a))   # fft frequencies for a given length
    +f = np.fft.fftfreq(len(a))   # fft frequencies
     np.fft.fftshift(f)           # shifts zero frequency to the middle
     np.fft.rfft(a)               # real fourier transform of a
    -np.fft.rfftfreq(len(a))      # real fft frequencies for a given length
    +np.fft.rfftfreq(len(a)) # real fft frequencies

    rounding

    @@ -401,11 +402,12 @@

    rounding

    random variables

    -
    np.random.normal(loc=0, scale=2, size=100)  # 100 normal distributed random numbers
    -np.random.seed(23032)                       # resets the seed value
    -np.random.rand(200)                         # 200 random numbers in [0, 1)
    -np.random.uniform(1, 30, 200)               # 200 random numbers in [1, 30)
    -np.random.randint(1, 16, 300)               # 300 random integers between [1, 16)
    +
    from np.random import normal, seed, rand, uniform, randint
    +normal(loc=0, scale=2, size=100)  # 100 normal distributed
    +seed(23032)                       # resets the seed value
    +rand(200)                         # 200 random numbers in [0, 1)
    +uniform(1, 30, 200)               # 200 random numbers in [1, 30)
    +randint(1, 16, 300)               # 300 random integers in [1, 16)

    @@ -413,10 +415,10 @@

    Matplotlib (import mat

    figures and axes

    -
    fig = plt.figure(figsize=(5, 2))                  # initialize figure
    -ax = fig.add_subplot(3, 2, 2)                     # add second subplot in a 3 x 2 grid
    -fig, axes = plt.subplots(5, 2, figsize=(5, 5))    # return fig and 5 x 2 array of axes
    -ax = fig.add_axes([left, bottom, width, height])  # add custom axis
    +
    fig = plt.figure(figsize=(5, 2))  # initialize figure
    +ax = fig.add_subplot(3, 2, 2)     # add second subplot in a 3 x 2 grid
    +fig, axes = plt.subplots(5, 2, figsize=(5, 5)) # fig and 5 x 2 nparray of axes
    +ax = fig.add_axes([left, bottom, width, height]) # add custom axis

    figures and axes properties

    @@ -442,8 +444,8 @@

    plotting routines

    ax.scatter(x,y, s=20, c=color) # scatter plot ax.pcolormesh(xx, yy, zz, shading='gouraud') # fast colormesh ax.colormesh(xx, yy, zz, norm=norm) # slower colormesh -ax.contour(xx, yy, zz, cmap='jet') # contour line plot -ax.contourf(xx, yy, zz, vmin=2, vmax=4) # filled contours plot +ax.contour(xx, yy, zz, cmap='jet') # contour lines +ax.contourf(xx, yy, zz, vmin=2, vmax=4) # filled contours n, bins, patch = ax.hist(x, 50) # histogram ax.imshow(matrix, origin='lower', extent=(x1, x2, y1, y2)) # show image @@ -456,14 +458,14 @@

    Scipy (import scipy as sci)

    interpolation

    -
    from scipy.ndimage import map_coordinates       # interpolates a data
    -pts_new = map_coordinates(data, float_indices,  # array at index coordinate
    -                          order=3)              # positions
    +
    from scipy.ndimage import map_coordinates       # interpolates data
    +pts_new = map_coordinates(data, float_indices,  # at index positions
    +                          order=3)

    Integration

    -
    from scipy.integrate import quad
    -value = quad(func, low_lim, up_lim)  # definite integral of python function
    +
    from scipy.integrate import quad     # definite integral of python
    +value = quad(func, low_lim, up_lim)  # function/method
    diff --git a/stylesheets/stylesheet.css b/stylesheets/stylesheet.css index 1ffd8ef..9b1cc6e 100644 --- a/stylesheets/stylesheet.css +++ b/stylesheets/stylesheet.css @@ -105,17 +105,17 @@ a { font-size: 1rem; } } .main-content { - column-count:auto; - -moz-column-count:auto; - -webkit-column-count: auto; - box-sizing: unset;} .main-content .group { display: inline-block; - -webkit-column-width: 500px; - -moz-column-width: 500px; - column-width: 500px; + column-count:auto; + -moz-column-count:auto; + -webkit-column-count: auto; + + -webkit-column-width: 570px; + -moz-column-width: 570px; + column-width: 570px; border-radius: 25px; border-size:2px; @@ -128,7 +128,7 @@ a { .main-content .subgroup{ display: inline-block; - width: 500px;} + width: 570px;} .main-content :first-child { margin-top: 0; } From 18ef2f501d9bf966aed5d4d8fae17ee0c1fade4f Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 13 Jun 2016 15:19:09 +0000 Subject: [PATCH 59/96] rebuild pages at a16ad11 --- index.html | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/index.html b/index.html index 1c97a92..9db27d5 100644 --- a/index.html +++ b/index.html @@ -207,13 +207,15 @@

    Control Flow

    Functions, Classes, Generators, Decorators

    -
    # Function
    +
    # Function groups code statements and possibly
    +# returns a derived value
     def myfunc(a1, a2):
         return a1 + a2
     
     x = myfunc(a1, a2)
     
    -# Class
    +# Class groups attributes (data)
    +# and associated methods (functions)
     class Point(object):
         def __init__(self, x):
             self.x = x
    @@ -222,17 +224,18 @@ 

    Functions, Classes, Generators, x = Point(3) -# Generators +# Generator iterates without +# creating all values at ones def firstn(n): num = 0 while num < n: yield num num += 1 -# consume the generator with list comprehension x = [i for i in firstn(10)] -# Decorators +# Decorator can be used to modify +# the behaviour of a function class myDecorator(object): def __init__(self, f): self.f = f From b0a0e229c767eb47271c3fae7cc4881be2d56c0e Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 13 Jun 2016 15:21:16 +0000 Subject: [PATCH 60/96] rebuild pages at 8449bc5 --- index.html | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/index.html b/index.html index 9db27d5..ad0a8a2 100644 --- a/index.html +++ b/index.html @@ -472,12 +472,11 @@

    Integration

    -

    Pandas

    +

    Pandas (import pandas as pd)

    Data structures

    -
    import pandas as pd                                     # import pandas
    -s = pd.Series(np.random.rand(1000), index=range(1000))  # series
    +
    s = pd.Series(np.random.rand(1000), index=range(1000))  # series
     index = pd.date_range("13/06/2016", periods=1000)       # time index
     df = pd.DataFrame(np.zeros(1000, 3), index=index,
                         columns=["A", "B", "C"])            # DataFrame
    From 44f810a22672d2c3c0bef75499f0df7f3df8813e Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 13 Jun 2016 16:05:29 +0000 Subject: [PATCH 61/96] rebuild pages at 761fc07 --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index ad0a8a2..eb0e26a 100644 --- a/index.html +++ b/index.html @@ -478,7 +478,7 @@

    Pandas (import pandas as pd)Data structures

    s = pd.Series(np.random.rand(1000), index=range(1000))  # series
     index = pd.date_range("13/06/2016", periods=1000)       # time index
    -df = pd.DataFrame(np.zeros(1000, 3), index=index,
    +df = pd.DataFrame(np.zeros([1000, 3]), index=index,
                         columns=["A", "B", "C"])            # DataFrame
    From 9b1c9c2c0c6362d4f04d08dc3569dda123e1d8ad Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 13 Jun 2016 16:06:06 +0000 Subject: [PATCH 62/96] rebuild pages at 7b1e7c3 --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index eb0e26a..c0c4c43 100644 --- a/index.html +++ b/index.html @@ -478,7 +478,7 @@

    Pandas (import pandas as pd)Data structures

    s = pd.Series(np.random.rand(1000), index=range(1000))  # series
     index = pd.date_range("13/06/2016", periods=1000)       # time index
    -df = pd.DataFrame(np.zeros([1000, 3]), index=index,
    +df = pd.DataFrame(np.zeros((1000, 3)), index=index,
                         columns=["A", "B", "C"])            # DataFrame
    From 4e8d9f12d529e4477a7e5b2c14eaf3e010ae2c6b Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Tue, 14 Jun 2016 08:00:46 +0000 Subject: [PATCH 63/96] rebuild pages at de6cd5d --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index c0c4c43..9fe6b65 100644 --- a/index.html +++ b/index.html @@ -69,7 +69,7 @@

    Scientific Python Cheatsheet

  • Control Flow
  • Functions, Classes, Generators, Decorators
  • -
  • IPython +
  • IPython
    • Python Console
    • Debugger commands
    • From bcc94a15887279444b1564af3701aa769e699ad4 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Tue, 14 Jun 2016 08:02:12 +0000 Subject: [PATCH 64/96] rebuild pages at 2583d43 --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index 9fe6b65..2cb4179 100644 --- a/index.html +++ b/index.html @@ -99,7 +99,7 @@

      Scientific Python Cheatsheet

    • interpolation
    • integration
  • -
  • Pandas +
  • Pandas
    • data structures
    • DataFrame
    • From 4e31496c2684a85fb83d39b0d076c91dacbb7049 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Tue, 14 Jun 2016 13:33:08 +0000 Subject: [PATCH 65/96] rebuild pages at 59108f7 --- index.html | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/index.html b/index.html index 2cb4179..d6a790a 100644 --- a/index.html +++ b/index.html @@ -74,7 +74,7 @@

      Scientific Python Cheatsheet

    • Python Console
    • Debugger commands
  • -
  • NumPy +
  • NumPy
  • -
  • Matplotlib +
  • Matplotlib
  • -
  • Scipy +
  • Scipy
  • -
  • Pandas +
  • Pandas
    • data structures
    • DataFrame
    • From 4cc238f09116030a4fc178658d3c5011f62cb1a6 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Wed, 15 Jun 2016 09:39:23 +0000 Subject: [PATCH 66/96] rebuild pages at 03b759c --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index d6a790a..1c35e4a 100644 --- a/index.html +++ b/index.html @@ -81,7 +81,7 @@

      Scientific Python Cheatsheet

    • array properties and operations
    • boolean arrays
    • elementwise operations and math functions
    • -
    • inner / outer products
    • +
    • inner / outer products
    • reading/ writing files
    • interpolation, integration, optimization
    • fft
    • From bf7650815ef1184e84323137a8674ba1bd92a6a2 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Wed, 15 Jun 2016 14:47:42 +0000 Subject: [PATCH 67/96] rebuild pages at cd0ecc0 --- index.html | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/index.html b/index.html index 1c35e4a..7cc4ff7 100644 --- a/index.html +++ b/index.html @@ -254,7 +254,7 @@

      Functions, Classes, Generators,

      IPython

      -

      Python console

      +

      console

      <object>?  # Information about the object
       <object>.<TAB>  # tab completion
       
      @@ -282,7 +282,7 @@ 

      Python console

      %reset
      -

      Debugger commands

      +

      Debugger console

      n               # execute next line
       b 42            # set breakpoint in the main file at line 42
       b myfile.py:42  # set breakpoint in 'myfile.py' at line 42
      @@ -295,6 +295,10 @@ 

      Debugger commands

      pp locals() # show all variables in local scope pp globals() # show all variables in global scope
      +
      +

      command line

      +
      ipython --pdb -- myscript.py argument1 --option1  # automatic debugger after exception
      +

      NumPy (import numpy as np)

      From bf87af2f73415ded0275fa3a93cd0dc646a236ef Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Wed, 15 Jun 2016 14:49:17 +0000 Subject: [PATCH 68/96] rebuild pages at 431e551 --- index.html | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/index.html b/index.html index 7cc4ff7..206a705 100644 --- a/index.html +++ b/index.html @@ -71,8 +71,9 @@

      Scientific Python Cheatsheet

  • IPython
  • NumPy
      @@ -282,7 +283,7 @@

      console

      %reset
  • -

    Debugger console

    +

    debugger

    n               # execute next line
     b 42            # set breakpoint in the main file at line 42
     b myfile.py:42  # set breakpoint in 'myfile.py' at line 42
    
    From bdc8cd9901d325ba13c687df56f9305ebeee1332 Mon Sep 17 00:00:00 2001
    From: Thomas Belahi 
    Date: Wed, 15 Jun 2016 22:35:05 +0000
    Subject: [PATCH 69/96] rebuild pages at fb72aaf
    
    ---
     index.html | 3 ++-
     1 file changed, 2 insertions(+), 1 deletion(-)
    
    diff --git a/index.html b/index.html
    index 206a705..8275ce3 100644
    --- a/index.html
    +++ b/index.html
    @@ -298,7 +298,8 @@ 

    debugger

    command line

    -
    ipython --pdb -- myscript.py argument1 --option1  # automatic debugger after exception
    +
    ipython --pdb -- myscript.py argument1 --option1  # debug after exception
    +ipython -i -- myscript.py argument1 --option1     # console after finish
    From c5e77ee8b56e20b0e3c1406e7c0e3e6520f07352 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Thu, 16 Jun 2016 13:08:18 +0000 Subject: [PATCH 70/96] rebuild pages at 529648b --- index.html | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/index.html b/index.html index 8275ce3..ac07c11 100644 --- a/index.html +++ b/index.html @@ -489,10 +489,10 @@

    Data structures

    DataFrame

    -
    df = pd.read_csv("filename.csv")           # read and load CSV file in a DataFrame
    -print(df[:2])                              # print first 2 lines of the DataFrame
    -raw = df.values                            # get raw data out of DataFrame object
    -cols = df.columns                          # get list of columns headers
    +
    df = pd.read_csv("filename.csv")   # read and load CSV file in a DataFrame
    +print(df[:2])                      # print first 2 lines of the DataFrame
    +raw = df.values                    # get raw data out of DataFrame object
    +cols = df.columns                  # get list of columns headers
    From 689dae6b20c52063f8df8a16fa113129c605ed19 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Wed, 29 Jun 2016 12:20:18 +0000 Subject: [PATCH 71/96] rebuild pages at 0ae1f39 --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index ac07c11..a3330a4 100644 --- a/index.html +++ b/index.html @@ -3,7 +3,7 @@ - + Scientific python cheat sheet by IPGP From 16bcfa54a6126219af332f2b560d0f99b94374f1 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Wed, 29 Jun 2016 13:17:29 +0000 Subject: [PATCH 72/96] rebuild pages at 448a20c --- index.html | 1 + 1 file changed, 1 insertion(+) diff --git a/index.html b/index.html index a3330a4..7e1a929 100644 --- a/index.html +++ b/index.html @@ -3,6 +3,7 @@ + Scientific python cheat sheet by IPGP From 467b5e7974f8fda3232f935096cbab245d35d956 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Wed, 6 Jul 2016 16:08:39 +0000 Subject: [PATCH 73/96] rebuild pages at 143c8a5 --- index.html | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/index.html b/index.html index 7e1a929..39d080d 100644 --- a/index.html +++ b/index.html @@ -140,7 +140,8 @@

    Dictionaries

    a = {'red': 'rouge', 'blue': 'bleu'}         # dictionary
     b = a['red']                                 # translate item
     c = [value for key, value in a.items()]      # loop through contents
    -d = a.get('yellow', 'no translation found')  # return default
    +d = a.get('yellow', 'no translation found') # return default +e = a.setdefault(extra, []).append('cyan') # append to (non-existing) item

    Strings

    @@ -460,7 +461,8 @@

    plotting routines

    ax.imshow(matrix, origin='lower', extent=(x1, x2, y1, y2)) # show image ax.specgram(y, FS=0.1, noverlap=128, - scale='linear') # plot a spectrogram
    + scale='linear') # plot a spectrogram +ax.text(x, y, string, fontsize=12, color='m') # write text
    From 68f9de2f0087e57c15f72662af732835f8111c3a Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Wed, 6 Jul 2016 16:45:49 +0000 Subject: [PATCH 74/96] rebuild pages at f55b6e5 --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index 39d080d..3e4a021 100644 --- a/index.html +++ b/index.html @@ -141,7 +141,7 @@

    Dictionaries

    b = a['red'] # translate item c = [value for key, value in a.items()] # loop through contents d = a.get('yellow', 'no translation found') # return default -e = a.setdefault(extra, []).append('cyan') # append to (non-existing) item +e = a.setdefault('extra', []).append('cyan') # append to (non-existing) item

    Strings

    From 304b08f1b17f5d4b1a180898a4af3976b13b6fc1 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Wed, 6 Jul 2016 16:50:15 +0000 Subject: [PATCH 75/96] rebuild pages at c80dfaf --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index 3e4a021..ef47b84 100644 --- a/index.html +++ b/index.html @@ -141,7 +141,7 @@

    Dictionaries

    b = a['red'] # translate item c = [value for key, value in a.items()] # loop through contents d = a.get('yellow', 'no translation found') # return default -e = a.setdefault('extra', []).append('cyan') # append to (non-existing) item +a.setdefault('extra', []).append('cyan') # init key with default

    Strings

    From d57e7e82af72291595e9ca49febcfbd4ac8ac1f6 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Wed, 6 Jul 2016 16:50:20 +0000 Subject: [PATCH 76/96] rebuild pages at 0ca9cfe --- index.html | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/index.html b/index.html index ef47b84..d8234da 100644 --- a/index.html +++ b/index.html @@ -137,11 +137,11 @@

    Lists

    Dictionaries

    -
    a = {'red': 'rouge', 'blue': 'bleu'}         # dictionary
    -b = a['red']                                 # translate item
    -c = [value for key, value in a.items()]      # loop through contents
    -d = a.get('yellow', 'no translation found')  # return default
    -a.setdefault('extra', []).append('cyan')     # init key with default
    +
    a = {'red': 'rouge', 'blue': 'bleu'}          # dictionary
    +b = a['red']                                  # translate item
    +c = [value for key, value in a.items()]       # loop through contents
    +d = a.get('yellow', 'no translation found')   # return default
    +e = a.setdefault('extra', []).append('cyan')  # init key with default

    Strings

    From 498087869e804f0bf3a40b7b58304f5f08b9a3f7 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 18 Jul 2016 08:22:35 +0000 Subject: [PATCH 77/96] rebuild pages at bc14f81 --- index.html | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/index.html b/index.html index d8234da..b8f1783 100644 --- a/index.html +++ b/index.html @@ -137,11 +137,11 @@

    Lists

    Dictionaries

    -
    a = {'red': 'rouge', 'blue': 'bleu'}          # dictionary
    -b = a['red']                                  # translate item
    -c = [value for key, value in a.items()]       # loop through contents
    -d = a.get('yellow', 'no translation found')   # return default
    -e = a.setdefault('extra', []).append('cyan')  # init key with default
    +
    a = {'red': 'rouge', 'blue': 'bleu'}         # dictionary
    +b = a['red']                                 # translate item
    +c = [value for key, value in a.items()]      # loop through contents
    +d = a.get('yellow', 'no translation found')  # return default
    +a.setdefault('extra', []).append('cyan')     # init key with default

    Strings

    @@ -265,6 +265,10 @@

    console

    %timeit range(1000) 100000 loops, best of 3: 7.76 us per loop +# run statement with python profiler +%prun <statement> +%prun -s <key> <statement> # sort by key, e.g. "cumulative" or "calls" + # run scripts and debug %run %run -d # run in debug mode @@ -282,7 +286,10 @@

    console

    !make # prefix command with "!" # clean namespace -%reset +%reset + +# run code from clipboard +%paste

    debugger

    From 4948368d1d2acd5322061e8b762bc1f2c4137e21 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 18 Jul 2016 08:32:45 +0000 Subject: [PATCH 78/96] rebuild pages at 61d0ddd --- index.html | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/index.html b/index.html index b8f1783..7abe8f6 100644 --- a/index.html +++ b/index.html @@ -129,8 +129,9 @@

    Lists

    d = [nu**2 for nu in b if nu < 3] # conditioned list comprehension e = c[0] # access element f = c[1:2] # access a slice of the list -g = ['re', 'bl'] + ['gr'] # list concatenation -h = ['re'] * 5 # repeat a list +g = c[-1] # access last element +h = ['re', 'bl'] + ['gr'] # list concatenation +i = ['re'] * 5 # repeat a list ['re', 'bl'].index('re') # returns index of 're' 're' in ['re', 'bl'] # true if 're' in list sorted([3, 2, 1]) # returns sorted list @@ -332,6 +333,7 @@

    indexing

    a = np.arange(100)          # initialization with 0 - 99
     a[:3] = 0                   # set the first three indices to zero
     a[2:5] = 1                  # set indices 2-4 to 1
    +a[:-3] = 2                  # set all but last three elements to 2
     a[start:stop:step]          # general form of indexing/slicing
     a[None, :]                  # transform to column vector
     a[[1, 1, 3, 8]]             # return array with values of the indices
    
    From cd951ad5ad59bc55d74d9d870717a5cd1a9ac516 Mon Sep 17 00:00:00 2001
    From: Thomas Belahi 
    Date: Tue, 19 Jul 2016 09:42:28 +0000
    Subject: [PATCH 79/96] rebuild pages at 19f0095
    
    ---
     index.html | 11 ++++++++++-
     1 file changed, 10 insertions(+), 1 deletion(-)
    
    diff --git a/index.html b/index.html
    index 7abe8f6..7bfa3af 100644
    --- a/index.html
    +++ b/index.html
    @@ -351,11 +351,13 @@ 

    array properties and operations

    a.flatten() # collapse array to one dimension a.conj() # return complex conjugate a.astype(np.int16) # cast to integer +a.tolist() # convert (possibly multidimensional) array to list np.argmax(a, axis=1) # return index of maximum along a given axis np.cumsum(a) # return cumulative sum np.any(a) # True if any element is True np.all(a) # True if all elements are True -np.argsort(a, axis=1) # return sorted index array along axis
    +np.argsort(a, axis=1) # return sorted index array along axis +np.where(a, x, y) # Construct array with elements from x or y depending on a

    boolean arrays

    @@ -393,6 +395,13 @@

    inner / outer products

    np.sum(a * a.T) # matrix norm
    +

    Linear algebra/Matrix math

    +
    from scipy import linalg
    +linalg.eigh(a)      # Find eigenvalues and eigenvectors
    +linalg.expm(a)      # Matrix exponential
    +linalg.logm(a)      # Matrix logarithm
    +
    +

    reading/ writing files

    
     np.fromfile(fname/fobject, dtype=np.float32, count=5)  # binary data from file
    
    From 5e7df1e1599e17ff802a2b0e161cb91c7082a358 Mon Sep 17 00:00:00 2001
    From: Thomas Belahi 
    Date: Tue, 19 Jul 2016 10:55:46 +0000
    Subject: [PATCH 80/96] rebuild pages at 9fb7f31
    
    ---
     index.html | 3 ++-
     1 file changed, 2 insertions(+), 1 deletion(-)
    
    diff --git a/index.html b/index.html
    index 7bfa3af..44d7886 100644
    --- a/index.html
    +++ b/index.html
    @@ -84,6 +84,7 @@ 

    Scientific Python Cheatsheet

  • boolean arrays
  • elementwise operations and math functions
  • inner / outer products
  • +
  • linear algebra / matrix math
  • reading/ writing files
  • interpolation, integration, optimization
  • fft
  • @@ -395,7 +396,7 @@

    inner / outer products

    np.sum(a * a.T) # matrix norm
    -

    Linear algebra/Matrix math

    +

    linear algebra / matrix math

    from scipy import linalg
     linalg.eigh(a)      # Find eigenvalues and eigenvectors
     linalg.expm(a)      # Matrix exponential
    
    From 984be6498cd3cbc949bbf94c0a722799ed6c2dd8 Mon Sep 17 00:00:00 2001
    From: Thomas Belahi 
    Date: Tue, 19 Jul 2016 10:56:30 +0000
    Subject: [PATCH 81/96] rebuild pages at d86024d
    
    ---
     index.html | 4 ++--
     1 file changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/index.html b/index.html
    index 44d7886..93401d6 100644
    --- a/index.html
    +++ b/index.html
    @@ -83,8 +83,8 @@ 

    Scientific Python Cheatsheet

  • array properties and operations
  • boolean arrays
  • elementwise operations and math functions
  • -
  • inner / outer products
  • -
  • linear algebra / matrix math
  • +
  • inner / outer products
  • +
  • linear algebra / matrix math
  • reading/ writing files
  • interpolation, integration, optimization
  • fft
  • From 9f5792afdfb7f98fa5803bb882f7f4fcf20ecb04 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Tue, 19 Jul 2016 11:01:47 +0000 Subject: [PATCH 82/96] rebuild pages at c7bc24d --- index.html | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/index.html b/index.html index 93401d6..4af9674 100644 --- a/index.html +++ b/index.html @@ -100,6 +100,7 @@

    Scientific Python Cheatsheet

  • Scipy
  • Pandas @@ -397,10 +398,8 @@

    inner / outer products

  • linear algebra / matrix math

    -
    from scipy import linalg
    -linalg.eigh(a)      # Find eigenvalues and eigenvectors
    -linalg.expm(a)      # Matrix exponential
    -linalg.logm(a)      # Matrix logarithm
    +
    evals, evecs = np.linalg.eig(a)      # Find eigenvalues and eigenvectors
    +evals, evecs = np.linalg.eigh(a)     # np.linalg.eig for hermitian matrix

    reading/ writing files

    @@ -498,6 +497,14 @@

    Integration

    from scipy.integrate import quad     # definite integral of python
     value = quad(func, low_lim, up_lim)  # function/method
    +
    +

    linear algebra / matrix math

    +
    from scipy import linalg
    +evals, evecs = linalg.eig(a)      # Find eigenvalues and eigenvectors
    +evals, evecs = linalg.eigh(a)     # linalg.eig for hermitian matrix
    +b = linalg.expm(a)                # Matrix exponential
    +c = linalg.logm(a)                # Matrix logarithm
    +

    Pandas (import pandas as pd)

    From c78894f62f5b9581e698ec62c8a381a6ca4c6e71 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Tue, 19 Jul 2016 11:02:57 +0000 Subject: [PATCH 83/96] rebuild pages at 3d37726 --- index.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/index.html b/index.html index 4af9674..2c7a518 100644 --- a/index.html +++ b/index.html @@ -100,7 +100,7 @@

    Scientific Python Cheatsheet

  • Scipy
  • Pandas @@ -498,7 +498,7 @@

    Integration

    value = quad(func, low_lim, up_lim) # function/method
    -

    linear algebra / matrix math

    +

    linear algebra

    from scipy import linalg
     evals, evecs = linalg.eig(a)      # Find eigenvalues and eigenvectors
     evals, evecs = linalg.eigh(a)     # linalg.eig for hermitian matrix
    
    From 03344a173d83019ab14d3bfac99d91977d8b5413 Mon Sep 17 00:00:00 2001
    From: Thomas Belahi 
    Date: Tue, 19 Jul 2016 11:12:55 +0000
    Subject: [PATCH 84/96] rebuild pages at 52aabaf
    
    ---
     index.html | 3 ++-
     1 file changed, 2 insertions(+), 1 deletion(-)
    
    diff --git a/index.html b/index.html
    index 2c7a518..a8af27d 100644
    --- a/index.html
    +++ b/index.html
    @@ -359,7 +359,8 @@ 

    array properties and operations

    np.any(a) # True if any element is True np.all(a) # True if all elements are True np.argsort(a, axis=1) # return sorted index array along axis -np.where(a, x, y) # Construct array with elements from x or y depending on a
    +np.where(cond) # return indices where cond is True +np.where(cond, x, y) # return elements from x or y depending on cond

    boolean arrays

    From ab24940dc695645ebf55ff32c790da736a165f03 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Tue, 19 Jul 2016 11:15:33 +0000 Subject: [PATCH 85/96] rebuild pages at 918b8ca --- index.html | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/index.html b/index.html index a8af27d..38bc04b 100644 --- a/index.html +++ b/index.html @@ -83,8 +83,8 @@

    Scientific Python Cheatsheet

  • array properties and operations
  • boolean arrays
  • elementwise operations and math functions
  • -
  • inner / outer products
  • -
  • linear algebra / matrix math
  • +
  • inner/ outer products
  • +
  • linear algebra/ matrix math
  • reading/ writing files
  • interpolation, integration, optimization
  • fft
  • @@ -387,7 +387,7 @@

    elementwise operations and ma np.std(a, axis=1) # standard deviation
    -

    inner / outer products

    +

    inner/ outer products

    np.dot(a, b)                  # inner product: a_mi b_in
     np.einsum('ij,kj->ik', a, b)  # einstein summation convention
     np.sum(a, axis=1)             # sum over axis 1
    @@ -398,7 +398,7 @@ 

    inner / outer products

    np.sum(a * a.T) # matrix norm
    -

    linear algebra / matrix math

    +

    linear algebra/ matrix math

    evals, evecs = np.linalg.eig(a)      # Find eigenvalues and eigenvectors
     evals, evecs = np.linalg.eigh(a)     # np.linalg.eig for hermitian matrix
    From b15c440868f5547e55d52f1c8375187209a9c167 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Tue, 19 Jul 2016 15:12:04 +0000 Subject: [PATCH 86/96] rebuild pages at a950fb2 --- index.html | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/index.html b/index.html index 38bc04b..48baffa 100644 --- a/index.html +++ b/index.html @@ -261,25 +261,26 @@

    IPython

    console

    -
    <object>?  # Information about the object
    -<object>.<TAB>  # tab completion
    +
    <object>?                   # Information about the object
    +<object>.<TAB>              # tab completion
     
    -# measure runtime of a function:
    +# run script
    +%run myscript.py
    +
    +# measure runtime:
     %timeit range(1000)
     100000 loops, best of 3: 7.76 us per loop
    +%run -t  myscript.py        # measures execution time
     
    -# run statement with python profiler
    +# run with profiler
     %prun <statement>
     %prun -s <key> <statement>  # sort by key, e.g. "cumulative" or "calls"
    +%run -p  myfile.py          # profile script
     
    -# run scripts and debug
    -%run
    -%run -d  # run in debug mode
    -%run -t  # measures execution time
    -%run -p  # runs a profiler
    -%debug  # jumps to the debugger after an exception
    -
    -%pdb  # run debugger automatically on exception
    +# run with debugger
    +%run -d myscript.py         # run in debug mode
    +%debug                      # jumps to the debugger after an exception
    +%pdb                        # run debugger automatically on exception
     
     # examine history
     %history
    
    From dc34b0c33183a20b11de0ae673586f323b291383 Mon Sep 17 00:00:00 2001
    From: Thomas Belahi 
    Date: Tue, 19 Jul 2016 15:13:47 +0000
    Subject: [PATCH 87/96] rebuild pages at c7123b8
    
    ---
     index.html | 14 +++++---------
     1 file changed, 5 insertions(+), 9 deletions(-)
    
    diff --git a/index.html b/index.html
    index 48baffa..7475438 100644
    --- a/index.html
    +++ b/index.html
    @@ -264,21 +264,17 @@ 

    console

    <object>?                   # Information about the object
     <object>.<TAB>              # tab completion
     
    -# run script
    +# run scripts / profile / debug
     %run myscript.py
     
    -# measure runtime:
    -%timeit range(1000)
    -100000 loops, best of 3: 7.76 us per loop
    -%run -t  myscript.py        # measures execution time
    +%timeit range(1000)         # measure runtime of statement
    +%run -t  myscript.py        # measure script execution time
     
    -# run with profiler
    -%prun <statement>
    +%prun <statement>           # run statement with profiler
     %prun -s <key> <statement>  # sort by key, e.g. "cumulative" or "calls"
     %run -p  myfile.py          # profile script
     
    -# run with debugger
    -%run -d myscript.py         # run in debug mode
    +%run -d myscript.py         # run script in debug mode
     %debug                      # jumps to the debugger after an exception
     %pdb                        # run debugger automatically on exception
     
    
    From 7047e0183853bc196d727fa06f2b3ba8c76ba688 Mon Sep 17 00:00:00 2001
    From: Thomas Belahi 
    Date: Fri, 29 Jul 2016 09:38:59 +0000
    Subject: [PATCH 88/96] rebuild pages at 491e859
    
    ---
     index.html | 4 ++--
     1 file changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/index.html b/index.html
    index 7475438..4eb70e9 100644
    --- a/index.html
    +++ b/index.html
    @@ -402,10 +402,10 @@ 

    linear algebra/ matrix math

    reading/ writing files

    
    -np.fromfile(fname/fobject, dtype=np.float32, count=5)  # binary data from file
     np.loadtxt(fname/fobject, skiprows=2, delimiter=',')   # ascii data from file
     np.savetxt(fname/fobject, array, fmt='%.5f')           # write ascii data
    -np.tofile(fname/fobject)                               # write (C) binary data
    +np.save(fname/fobject, array) # save binary data +np.load(fname/fobject, mmap_mode='c') # load binary data (memory mapped)

    interpolation, integration, optimization

    From 43ae76e809b8d5bfadb0feb102e931017022949c Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Fri, 29 Jul 2016 09:42:01 +0000 Subject: [PATCH 89/96] rebuild pages at 8547243 --- index.html | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/index.html b/index.html index 4eb70e9..edbc700 100644 --- a/index.html +++ b/index.html @@ -404,8 +404,10 @@

    reading/ writing files

    
     np.loadtxt(fname/fobject, skiprows=2, delimiter=',')   # ascii data from file
     np.savetxt(fname/fobject, array, fmt='%.5f')           # write ascii data
    -np.save(fname/fobject, array)                          # save binary data
    -np.load(fname/fobject, mmap_mode='c')                  # load binary data (memory mapped)
    +np.fromfile(fname/fobject, dtype=np.float32, count=5) # binary data from file +np.tofile(fname/fobject) # write (C) binary data +np.save(fname/fobject, array) # save as numpy binary (.npy) +np.load(fname/fobject, mmap_mode='c') # load .npy file (memory mapped)

    interpolation, integration, optimization

    From 182baffe24441b68060c34a79cbc53ed23b3b455 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Sat, 20 Aug 2016 13:43:45 +0000 Subject: [PATCH 90/96] rebuild pages at a75ee1c --- index.html | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/index.html b/index.html index edbc700..031a772 100644 --- a/index.html +++ b/index.html @@ -447,7 +447,8 @@

    figures and axes

    fig = plt.figure(figsize=(5, 2))  # initialize figure
     ax = fig.add_subplot(3, 2, 2)     # add second subplot in a 3 x 2 grid
     fig, axes = plt.subplots(5, 2, figsize=(5, 5)) # fig and 5 x 2 nparray of axes
    -ax = fig.add_axes([left, bottom, width, height]) # add custom axis
    +ax = fig.add_axes([left, bottom, width, height]) # add custom axis +fig.savefig('out.png') # save png image

    figures and axes properties

    @@ -488,9 +489,14 @@

    Scipy (import scipy as sci)

    interpolation

    -
    from scipy.ndimage import map_coordinates       # interpolates data
    -pts_new = map_coordinates(data, float_indices,  # at index positions
    -                          order=3)
    +
    # interpolate data at index positions:
    +from scipy.ndimage import map_coordinates
    +pts_new = map_coordinates(data, float_indices, order=3)
    +
    +# simple 1d interpolator with axis argument:
    +from scipy.interpolate import interp1d
    +interpolator = interp1d(x, y, axis=2, fill_value=0., bounds_error=False)
    +y_new = interpolator(x_new)

    Integration

    From 9df96c0511a9565ab616c86f26a5c80193938aa3 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Thu, 15 Sep 2016 10:14:28 +0000 Subject: [PATCH 91/96] rebuild pages at c839653 --- index.html | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/index.html b/index.html index 031a772..67acd3e 100644 --- a/index.html +++ b/index.html @@ -445,10 +445,11 @@

    Matplotlib (import mat

    figures and axes

    fig = plt.figure(figsize=(5, 2))  # initialize figure
    -ax = fig.add_subplot(3, 2, 2)     # add second subplot in a 3 x 2 grid
    +fig.savefig('out.png')            # save png image
     fig, axes = plt.subplots(5, 2, figsize=(5, 5)) # fig and 5 x 2 nparray of axes
    -ax = fig.add_axes([left, bottom, width, height]) # add custom axis
    -fig.savefig('out.png')            # save png image
    +ax = fig.add_subplot(3, 2, 2) # add second subplot in a 3 x 2 grid +ax = plt.subplot2grid((2, 2), (0, 0), colspan=2) # multi column/row axis +ax = fig.add_axes([left, bottom, width, height]) # add custom axis

    figures and axes properties

    From 09df7d227dcdb46a251080d13de8fc981d67a3fd Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Tue, 11 Oct 2016 09:42:25 +0000 Subject: [PATCH 92/96] rebuild pages at 011c463 --- index.html | 41 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/index.html b/index.html index 67acd3e..6c393ea 100644 --- a/index.html +++ b/index.html @@ -65,6 +65,7 @@

    Scientific Python Cheatsheet

  • Types
  • Lists
  • Dictionaries
  • +
  • Sets
  • Strings
  • Operators
  • Control Flow
  • @@ -135,16 +136,49 @@

    Lists

    h = ['re', 'bl'] + ['gr'] # list concatenation i = ['re'] * 5 # repeat a list ['re', 'bl'].index('re') # returns index of 're' +a.append('yellow') # add new element to end of list +a.extend(b) # add elements from list `b` to end of list `a` +a.insert(1, 'yellow') # insert element in specified position 're' in ['re', 'bl'] # true if 're' in list -sorted([3, 2, 1]) # returns sorted list +'fi' not in ['re', 'bl'] # true if 'fi' not in list +sorted([3, 2, 1]) # returns sorted list +a.pop(2) # remove and return item at index (default last)

    Dictionaries

    a = {'red': 'rouge', 'blue': 'bleu'}         # dictionary
     b = a['red']                                 # translate item
    +'red' in a                                   # true if dictionary a contains key 'red'
     c = [value for key, value in a.items()]      # loop through contents
     d = a.get('yellow', 'no translation found')  # return default
    -a.setdefault('extra', []).append('cyan')     # init key with default
    +a.setdefault('extra', []).append('cyan') # init key with default +a.update({'green': 'vert', 'brown': 'brun'}) # update dictionary by data from another one +a.keys() # get list of keys +a.values() # get list of values +a.items() # get list of key-value pairs +del a['red'] # delete key and associated with it value +a.pop('blue') # remove specified key and return the corresponding value +
    +
    +

    Sets

    +
    a = {1, 2, 3}                                # initialize manually
    +b = set(range(5))                            # initialize from iteratable
    +a.add(13)                                    # add new element to set
    +a.discard(13)                                # discard element from set
    +a.update([21, 22, 23])                       # update set with elements from iterable
    +a.pop()                                      # remove and return an arbitrary set element
    +2 in {1, 2, 3}                               # true if 2 in set
    +5 in {1, 2, 3}                               # true if 5 not in set
    +a.issubset(b)                                # test whether every element in a is in b
    +a <= b                                       # issubset in operator form
    +a.issuperset(b)                              # test whether every element in b is in a
    +a >= b                                       # issuperset in operator form
    +a.intersection(b)                            # return the intersection of two sets as a new set
    +a.difference(b)                              # return the difference of two or more sets as a new set
    +a - b                                        # difference in operator form
    +a.symmetric_difference(b)                    # return the symmetric difference of two sets as a new set
    +a.union(b)                                   # return the union of sets as a new set
    +c = frozenset()                              # the same as set but immutable

    Strings

    @@ -170,8 +204,11 @@

    Operators

    2 < 1 # smaller 1 != 2 # not equal 1 != 2 and 2 < 3 # logical AND +a & b # logical AND 1 != 2 or 2 < 3 # logical OR +a | b # logical OR not 1 == 2 # logical NOT +a ^ b # logical XOR 'a' in b # test if a is in b a is b # test if objects point to the same memory (id)
    From eb950b6145ebbb856082aa50d41d1861a39d71fe Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Tue, 11 Oct 2016 09:44:13 +0000 Subject: [PATCH 93/96] rebuild pages at 775a1fc --- index.html | 3 --- 1 file changed, 3 deletions(-) diff --git a/index.html b/index.html index 6c393ea..86c25bf 100644 --- a/index.html +++ b/index.html @@ -204,11 +204,8 @@

    Operators

    2 < 1 # smaller 1 != 2 # not equal 1 != 2 and 2 < 3 # logical AND -a & b # logical AND 1 != 2 or 2 < 3 # logical OR -a | b # logical OR not 1 == 2 # logical NOT -a ^ b # logical XOR 'a' in b # test if a is in b a is b # test if objects point to the same memory (id)

    From f5dfac6cb817e4bf9a57a1a34669f1b7120c5114 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Sun, 23 Oct 2016 12:07:49 +0000 Subject: [PATCH 94/96] rebuild pages at 3caf469 --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index 86c25bf..850112a 100644 --- a/index.html +++ b/index.html @@ -168,7 +168,7 @@

    Sets

    a.update([21, 22, 23]) # update set with elements from iterable a.pop() # remove and return an arbitrary set element 2 in {1, 2, 3} # true if 2 in set -5 in {1, 2, 3} # true if 5 not in set +5 not in {1, 2, 3} # true if 5 not in set a.issubset(b) # test whether every element in a is in b a <= b # issubset in operator form a.issuperset(b) # test whether every element in b is in a From 5b37194ee523ff180ec4dc9dee1dd4a58ad6ad6e Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Mon, 6 Mar 2017 09:23:00 +0000 Subject: [PATCH 95/96] rebuild pages at 9879e67 --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index 850112a..568654f 100644 --- a/index.html +++ b/index.html @@ -265,7 +265,7 @@

    Functions, Classes, Generators, x = Point(3) # Generator iterates without -# creating all values at ones +# creating all values at once def firstn(n): num = 0 while num < n: From a93619eea46298988274bfc31764e94a31641381 Mon Sep 17 00:00:00 2001 From: Thomas Belahi Date: Fri, 10 Mar 2017 09:56:46 +0000 Subject: [PATCH 96/96] rebuild pages at 13eb13c --- index.html | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/index.html b/index.html index 568654f..46a96ab 100644 --- a/index.html +++ b/index.html @@ -560,9 +560,38 @@

    Data structures

    DataFrame

    df = pd.read_csv("filename.csv")   # read and load CSV file in a DataFrame
    -print(df[:2])                      # print first 2 lines of the DataFrame
     raw = df.values                    # get raw data out of DataFrame object
    -cols = df.columns                  # get list of columns headers
    +cols = df.columns # get list of columns headers +df.dtypes # get data types of all columns +df.head(5) # get first 5 rows +df.describe() # get basic statisitics for all columns +df.index # get index column range + +#column slicin +# (.loc[] and .ix[] are inclusive of the range of values selected) +df.col_name # select column values as a series by column name (not optimized) +df[['col_name']] # select column values as a dataframe by column name (not optimized) +df.loc[:, 'col_name'] # select column values as a series by column name +df.loc[:, ['col_name']] # select column values as a dataframe by column name +df.iloc[:, 0] # select by column index +df.iloc[:, [0]] # select by column index, but as a dataframe +df.ix[:, 'col_name'] # hybrid approach with column name +df.ix[:, 0] # hybrid approach with column index + +# row slicin +print(df[:2]) # print first 2 rows of the dataframe +df.iloc[0:2, :] # select first 2 rows of the dataframe +df.loc[0:2,'col_name'] # select first 3 rows of the dataframe +df.loc[0:2, ['col_name1', 'col_name3', 'col_name6']] # select first 3 rows of the 3 different columns +df.iloc[0:2,0:2] # select fisrt 3 rows and first 3 columns +# Again, .loc[] and .ix[] are inclusive + +# Dicin +df[ df.col_name < 7 ] # select all rows where col_name < 7 +df[ (df.col_name1 < 7) & (df.col_name2 == 0) ] # combine multiple boolean indexing conditionals using bit-wise logical operators. + # Regular Python boolean operators (and, or) cannot be used here. + # Be sure to encapsulate each conditional in parenthesis to make this work. +df[df.recency < 7] = -100 # writing to slice