1. Introduction to NumPy arrays
Gert-Ludwig Ingold
‡ https://github.com/gertingold/euroscipy-numpy-tutorial.git
2. Python comes with batteries included
Ü extensive Python standard library
What about batteries for scientists (and others as well)?
Ü scientific Python ecosystem
from:
www.scipy.org
+ SciKits and many other packages
3. Python comes with batteries included
Ü extensive Python standard library
What about batteries for scientists (and others as well)?
Ü scientific Python ecosystem
from:
www.scipy.org
+ SciKits and many other packages
4. Python comes with batteries included
Ü extensive Python standard library
What about batteries for scientists (and others as well)?
Ü scientific Python ecosystem
from:
www.scipy.org
+ SciKits and many other packages
5. www.scipy-lectures.org
Python
Matplotlib
SciKits Numpy
SciPy
IPython
IP[y]:
Cython
2017
EDITION
Edited by
Gaël Varoquaux
Emmanuelle Gouillart
Olaf Vahtras
Scipy
Lecture Notes
www.scipy-lectures.org
Gaël Varoquaux • Emmanuelle Gouillart • Olav Vahtras
Christopher Burns • Adrian Chauve • Robert Cimrman • Christophe Combelles
Pierre de Buyl • Ralf Gommers • André Espaze • Zbigniew Jędrzejewski-Szmek
Valentin Haenel • Gert-Ludwig Ingold • Fabian Pedregosa • Didrik Pinte
Nicolas P. Rougier • Pauli Virtanen
and many others...
docs.scipy.org/doc/numpy/
8. List slicing
basic syntax: [start:stop:step]
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6 7 8
a[0:5] a[5:8]
I if step=1
I slice contains the elements start to stop-1
I slice contains stop-start elements
I start, stop, and also step can be negative
I default values:
I start 0, i.e. starting from the first element
I stop N, i.e up to and including the last element
I step 1
13. Problems with lists as matrices
I different axes are not treated on equal footing
I lists can contain arbitrary objects
matrices have a homogeneous structure
I list elements can be scattered in memory
Applied to matrices ...
...lists are conceptually inappropriate
...lists have less performance than possible
14. We need a new object
ndarray
multidimensional, homogeneous array of fixed-size items
17. Getting started
Import the NumPy package:
from numpy import *
from numpy import array, sin, cos
import numpy
18. Getting started
Import the NumPy package:
from numpy import *
from numpy import array, sin, cos
import numpy
import numpy as np
Ü
19. Getting started
Import the NumPy package:
from numpy import *
from numpy import array, sin, cos
import numpy
import numpy as np
Ü
Check the NumPy version:
np.__version__
20. Data types
Some important data types:
integer int8, int16, int32, int64, uint8, ...
float float16, float32, float64, ...
complex complex64, complex128, ...
boolean bool8
Unicode string
default type: float64
Beware of overflows!
22. Views
For the sake of efficiency, NumPy uses views if possible.
I Changing one or more matrix elements will change it in all views.
I Example: transposition of a matrix a.T
No need to copy the matrix and to create a new one
23. Some array creation routines
I numerical ranges: arange, linspace, logspace
I homogeneous data: zeros, ones
I diagonal elements: diag, eye
I random numbers: rand, randint
Numpy has an append()-method. Avoid it if possible.
24. Indexing and slicing in one dimension
1d arrays: indexing and slicing as for lists
I first element has index 0
I negative indices count from the end
I slices: [start:stop:step]
without the element indexed by stop
I if values are omitted:
I start: starting from first element
I stop: until (and including) the last element
I step: all elements between start and stop-1
25. Indexing and slicing in higher dimensions
I usual slicing syntax
I difference to lists:
slices for the various axes separated by comma
0
8
16
24
32
1
9
17
25
33
2
10
18
26
34
3
11
19
27
35
4
12
20
28
36
5
13
21
29
37
6
14
22
30
38
7
15
23
31
39
a[2, -3]
26. Indexing and slicing in higher dimensions
I usual slicing syntax
I difference to lists:
slices for the various axes separated by comma
0
8
16
24
32
1
9
17
25
33
2
10
18
26
34
3
11
19
27
35
4
12
20
28
36
5
13
21
29
37
6
14
22
30
38
7
15
23
31
39
a[:3, :5]
41. Mathematical functions in NumPy
Universal functions (ufuncs) take ndarrays as argument
Trigonometric functions
sin, cos, tan, arcsin, arccos, arctan, hypot, arctan2, degrees,
radians, unwrap, deg2rad, rad2deg
Hyperbolic functions
sinh, cosh, tanh, arcsinh, arccosh, arctanh
Rounding
around, round_, rint, fix, floor, ceil, trunc
Sums, products, differences
prod, sum, nansum, cumprod, cumsum, diff, ediff1d, gradient,
cross, trapz
Exponents and logarithms
exp, expm1, exp2, log, log10, log2, log1p, logaddexp, logaddexp2
Other special functions
i0, sinc
Floating point routines
signbit, copysign, frexp, ldexp
Arithmetic operations
add, reciprocal, negative, multiply, divide, power, subtract,
true_divide, floor_divide, fmod, mod, modf, remainder
Handling complex numbers
angle, real, imag, conj
Miscellaneous
convolve, clip, sqrt, square, absolute, fabs, sign, maximum,
minimum, fmax, fmin, nan_to_num, real_if_close, interp
Many more special functions are provided as ufuncs by SciPy
42. Rules for broadcasting
Arrays can be broadcast to the same shape if one of the following points
is fulfilled:
1. The arrays all have exactly the same shape.
2. The arrays all have the same number of dimensions and the length
of each dimension is either a common length or 1.
3. The arrays that have too few dimensions can have their shapes
prepended with a dimension of length 1 to satisfy property 2.
45. Application: π from random numbers
0
0
1
1
π/4
1. Create pairs of random numbers and
determine the fraction of pairs which
has a distance from the origin less
than one.
2. Multiply the result by four to obtain an
approximation of π.
hint: count_nonzero(a) counts the number of non-zero values in the
array a and also works for Boolean arrays. Remember that
np.info(...) can be helpful.
46. Fibonacci series and linear algebra
1 1
2
3
5
8
13
21
Fibonacci series:
1, 1, 2, 3, 5, 8, 13, 21, ...
Fn+1 = Fn + Fn−1, F1 = F2 = 1
or :
1 1
1 0
Fn
Fn−1
=
Fn+1
Fn
What is the limit of Fn+1/Fn for large n?
48. Linear algebra in NumPy
import numpy.linalg as LA
Matrix and vector products
dot, vdot, inner, outer, matmul, tensordot, einsum, LA.matrix_power, kron
Decompositions
LA.cholesky, LA.qr, LA.svd
Matrix eigenvalues
LA.eig, LA.eigh, LA.eigvals, LA.eigvalsh
Norms and other numbers
LA.norm, LA.cond, LA.det, LA.matrix_rank, LA.slogdet, trace
Solving equations and inverting matrices LA.solve, LA.tensorsolve, LA.lstsq,
LA.inv, LA.pinv, LA.tensorinv
hint: see also the methods for linear algebra in SciPy
49. Statistics in NumPy
Order statistics
amin, amax, nanmin, nanmax, ptp, percentile, nanpercentile
Averages and variances
median, average, mean, std, var, nanmedian, nanmean, nanstd, nanvar
Correlating
corrcoef, correlate, cov
Histograms
histogram, histogram2d, histogramdd, bincount, digitize
50. Application: Brownian motion
+1
-1
1. Simulate several trajectories for a one-dimensional Brownian
motion
hint: np.random.choice
2. Plot the mean distance from the origin as a function of time
3. Plot the variance of the trajectories as a function of time