6/3/2015

Numpy tutorial

Numpy tutorial
Nicolas P. Rougier

Introduction
The Game of Life
The way of python
The way of numpy
A step further
Exercises
Neophyte
Novice
Apprentice
Beyond this tutorial
Other Tutorials
Numpy documentation
Code documentation
Mailing lists
Quick references
Data type
Creation
Reshaping
Slicing
Broadcasting
Operations

Sources are available here. Figures are in the figures directory and all scripts are
located in the scripts directory.
All code and material is licensed under a Creative Commons Attribution 3.0
United States License (CC-by) http://creativecommons.org/licenses/by/3.0/us
Thanks to Nicky van Foreest for useful corrections.

Introduction
NumPy is the fundamental package for scientific computing with Python. It
contains among other things:
→
→
→
→

Besides its obvious scientific uses, NumPy can also be used as an efficient multidimensional container of generic data. Arbitrary data-types can be defined and
this allows NumPy to seamlessly and speedily integrate with a wide variety of
http://www.labri.fr/perso/nrougier/teaching/numpy/numpy.html

1/16

Every
cell interacts with its eight neighbours. We'll show in the following sections implementation of this game
using pure python and numpy in order to illustrate main differences with python
and numpy.
We'll first use a very simple setup and more precisely. unchanged.
The initial pattern constitutes the 'seed' of the system. We are going to explore numpy through a simple example. Any live cell with two or three live neighbours lives. It is the best-known
example of a cellular automaton.html
2/16
.
The Game of Life
Numpy is slanted toward scientific computing and we'll consider in this section
the game of life by John Conway which is one of the earliest example of cellular
automata (see figure below). which are the cells that are directly
horizontally. each generation is a pure
function of the one before. (In other words.
Figure 1 Simulation of the game of life.
3.) The rules continue to be applied repeatedly to
create further generations. needing no input
from human players. as if by needs caused by
underpopulation. the
following transitions occur:
1.
The universe of the Game of Life is an infinite two-dimensional orthogonal grid
of square cells. live or dead.
4. Any live cell with fewer than two live neighbours dies. also known simply as Life. as if by overcrowding. At each step in time. One interacts with the Game of Life by creating an initial
configuration and observing how it evolves. Any live cell with more than three live neighbours dies.
implementing the Game of Life. The "game" is actually a zero-player game. or diagonally adjacent.
The Game of Life.
2. to the next
generation.fr/perso/nrougier/teaching/numpy/numpy. and the discrete moment at which this
happens is sometimes called a tick. Those cellular automaton can be conveniently
considered as array of cells that are connected together through the notion of
neighbours. vertically. each of which is in one of two possible states. Any dead cell with exactly three live neighbours becomes a live cell.
Note
This is an excerpt from
wikipedia entry on Cellular
Automaton.labri. The first generation is
created by applying the above rules simultaneously to every cell in the seed –
births and deaths happen simultaneously.6/3/2015
Numpy tutorial
projects. we'll use the glider pattern
that is known to move one step diagonally in 4 iterations as illustrated below:
http://www.
meaning that its evolution is determined by its initial state. is a cellular automaton devised by
the British mathematician John Horton Conway in 1970.

0.0. 0.
[0. 0. 0. 0. 1.0]. we can check the program's correct:
>>> show(Z)
[0.html
3/16
. 0. 0]
[0.0.0. 0.
[0. len(Z[0])
N = [[0. 0]
[0.cols‐1):
for y in range(1. 1.1.0. len(Z[0])
N = compute_neighbours(Z)
for x in range(1. 0.0]. 0.
In pure python.rows‐1):
if Z[y][x] == 1 and (N[y][x] < 2 or N[y][x] > 3):
Z[y][x] = 0
elif Z[y][x] == 0 and N[y][x] == 3:
Z[y][x] = 1
return Z
Note
The show command is
supplied witht he script.0.rows‐1):
N[y][x] = Z[y‐1][x‐1]+Z[y][x‐1]+Z[y+1][x‐1] \
+ Z[y‐1][x] +Z[y+1][x] \
+ Z[y‐1][x+1]+Z[y][x+1]+Z[y+1][x+1]
return N
To iterate one step in time.0.0. 1. 0]
>>> for i in range(4): iterate(Z)
>>> show(Z)
[0. 0. 0]
[0.
The way of python
Note
We could have used the
more efficient python array
interface but people may be
more familiar with the list
object.0].0. 1]
You can download the full script here: game-of-life-python. 0.
[0.fr/perso/nrougier/teaching/numpy/numpy.labri.0.0]]
This board possesses a 0 border that allows to accelerate things a bit by
avoiding to have specific tests for borders when counting the number of
neighbours.1.6/3/2015
Numpy tutorial
t=0
t=1
t=2
t=3
t=4
This property will help us debug our scripts. First step is to count neighbours:
def compute_neighbours(Z):
rows.0.cols = len(Z). 1]
[0. 1]
[0.
Using a dedicated display function.0.1. 1.
[0. 1. we then simply count the number of neighbours for
each internal cell and we update the whole board according to the 4 rules:
def iterate(Z):
rows.0.0.py
http://www.0].
[0.0].]*(cols) for i in range(rows)]
for x in range(1.0. 1.cols‐1):
for y in range(1.0.cols = len(Z).0.1.0.0. we can code the Game of Life using a list of lists representing
the board where cells are supposed to evolve:
Z = [[0. 0]
[1.1.

6/3/2015
Numpy tutorial
The way of numpy
Note
There exists many more
different ways to create a
numpy array.shape
(6.0.
But even better.
[0.1]. numpy will then choose an
integer data type.1.0]])
>>> print Z.html
4/16
.0]
actually corresponds to Z[1.base is Z
True
http://www. This
can be done very easily with:
Note
For a complete review on
numpy data types.0. It is important to understand at this point that this is
really a subpart of Z in the sense that any change to this subpart will have
immediate impact on Z:
>>> A = Z[1:5.0.1.0].0.1:5]
>>> A[0.
[0.fr/perso/nrougier/teaching/numpy/numpy.
[0.0.0.0.0.0].0]. we actually extract a subpart of Z ranging from rows 1 to
5 and columns 1 to 5. This can be easily checked using:
>>> import numpy as np
>>> Z = np.0.0. we can also access a subpart of the array using the slice
notation:
>>> print Z[1:5.1.1:5]
[[0 0 1 0]
[1 0 1 0]
[0 1 1 0]
[0 0 0 0]]
In the example above. you can check easily if an array is part of another one:
>>> print Z. Since all elements are integers.
The first thing to do is to create the proper numpy array to hold the cells.0]. 6)
Each element of Z can be accessed using a row and a column index (in that order):
>>> print Z[0.1.0. check the
documentation.0] = 9
>>> print A
[[9 0 1 0]
[1 0 1 0]
[0 1 1 0]
[0 0 0 0]]
>>> print Z
[[0 0 0 0 0 0]
[0 9 0 1 0 0]
[0 1 0 1 0 0]
[0 0 1 1 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]]
We set the value of A[0.0.0.0.array([[0.0.dtype
int64
We can also check the shape of the array to make sure it is 6x6:
>>> print Z.0.base is None
True
>>> print A.0] to 9 and we see immediate change in Z[1.1. If in
doubt. numpy will
choose one for us. but things can become much more complex (we'll see that later). This may seem trivial with such simple
arrays.5]
0
Note
This element access is
actually called indexing and
this is very powerful tool for
vectorized computation.
Note that we did not specify the data type of the array and thus.0.
[0.labri.0.
[0.0].1] because
A[0.0.

zeros(Z. This concept of broadcasting is quite powerful and it will take you some time
before masterizing it fully (if even possible).1:‐1] + Z[2: . numpy complains about the
impossibility of broadcasting the two arrays together.‐1:1]
Traceback (most recent call last):
File "<stdin>". We could do it the same way
as for the python version. But we'll use vectorize computation using the following
code:
>>> N = np.
Ok.
How can a matrix and a scalar be added together ? Well. :‐2] + Z[ :‐2. in <module>
ValueError: operands could not be broadcast together with shapes (6. we
have (1+(2*Z+3))[i. this
is called vectorization. You'll acquire
this experience by using
numpy (of course) but also
by asking questions on the
mailing list
We now need a function to count the neighbours. Said differently.j] == (1+(2*Z[i..shape. :‐2] + Z[1:‐1.1:‐1] + Z[ :‐2.html
5/16
.6) (4.labri.
However.j. dtype=int)
>>> N[1:‐1.
First. so good.fr/perso/nrougier/teaching/numpy/numpy.
Ok. we won't
use broadcasting (uh ?).j]+3)) for any i. it saves you a lot of hassle.‐1:1] ?
>>> Z + Z[‐1:1. We would prefer to act on the whole array whenever possible.6/3/2015
Numpy tutorial
Counting neighbours
Note
It is not always possible to
vectorize computations and
it requires generally some
experience. but this would make things very slow because of the
nested loops. let's start then.2:] +
Z[1:‐1. so far.2:] +
Z[2: . line 1. Broadcasting is a very
powerful feature of numpy and most of the time. in the present case (counting neighbours if you remember).2:])
To understand this code. But numpy is
smart enough to guess that you actually want to add 1 to each of the element of
Z. they can't.4)
This raises a Value Error. let's
say Z[‐1:1. :‐2] + Z[2: . have a look at the figure below:
http://www. you need to know that you can manipulate Z as if (and only as if) it was a
regular scalar:
>>> print 1+(2*Z+3)
[[4 4 4 4 4 4]
[4 4 4 6 4 4]
[4 6 4 6 4 4]
[4 4 6 6 4 4]
[4 4 4 4 4 4]
[4 4 4 4 4 4]]
If you look carefully at the output. but more interestingly..
Let's consider for example the following code:
>>> print Z+1
[[1 1 1 1 1 1]
[1 1 1 2 1 1]
[1 2 1 2 1 1]
[1 1 2 2 1 1]
[1 1 1 1 1 1]
[1 1 1 1 1 1]]
Note
See also the broadcasting
section in the numpy
documentation.1:‐1] += (Z[ :‐2. Now what happens if we add Z with one of its subpart. you may realize that the ouptut corresponds
to the formula above applied individually to each element.

def iterate_2(Z):
# Count neighbours
N = (Z[0:‐2.2:] +
Z[1:‐1.argwhere( (Z_==1) & (N_ > 3) )
R3 = np.2:])
# Apply rules
birth = (N==3) & (Z[1:‐1..:] = Z[:.ravel()
Z_ = Z.2:] +
Z[2: .0:‐2] + Z[1:‐1.
In a first approach.ravel()
# Apply rules
R1 = np.1:‐1] + Z[0:‐2.argwhere( (Z_==1) & ((N_==2) | (N_==3)) )
R4 = np.1:‐1]==0)
survive = ((N==2) | (N==3)) & (Z[1:‐1.0:‐2] + Z[0:‐2.zeros(Z.1:‐1] + Z[2: .] = 0
Z[1:‐1. Since they have been chosen carefully.1:‐1] + Z[0:‐2.2:] +
Z[1:‐1.argwhere( (Z_==0) & (N_==3) )
# Set new values
Z_[R1] = 0
Z_[R2] = 0
Z_[R3] = Z_[R3]
Z_[R4] = 1
# Make sure borders stay null
Z[0.6/3/2015
Numpy tutorial
What we actually did with the above code is to add all the darker blue squares
together.labri. The right-hand side of these two expressions are in fact logical
expressions that will result in boolean arrays (just print them to check). If you want to convince yourself. it is far from optimal
because of the use of the 4 argwhere calls that may be quite slow.1:‐1]==1)
Z[. you'll see that these two variables are
indeed arrays.0:‐2] + Z[0:‐2.0:‐2] + Z[2: .0:‐2] + Z[1:‐1. We then
set all Z values to 0 (all cells become dead) and we use the birth and survive
arrays to conditionally set Z values to 1.fr/perso/nrougier/teaching/numpy/numpy.1:‐1] + Z[2: .1:‐1][birth | survive] = 1
return Z
If you look at the birth and survive lines. consider a cell in the lighter blue
area of the central sub-figure and check what will the result for a given cell. the result will be exactly what
we expected.
Iterate
Note
Note the use of the ravel
function that flatten an
array. And we're done ! Let's test this:
>>> print Z
[[0 0 0 0 0 0]
http://www.html
6/16
.:] = Z[‐1.
def iterate(Z):
# Iterate the game of life : naive version
# Count neighbours
N = np.argwhere( (Z_==1) & (N_ < 2) )
R2 = np.0] = Z[:. We can
instead take advantages of numpy features the following way. This is necessary since
the argwhere function
returns flattened indices.. we can write the iterate function using the argwhere method
that will give us the indices where a given condition is True.1:‐1] += (Z[0:‐2.2:] +
Z[2: .‐1] = 0
Even if this first version does not use nested loops.shape.0:‐2] + Z[2: . int)
N[1:‐1.2:])
N_ = N.

fr/perso/nrougier/teaching/numpy/numpy.
FAQ
General questions about numpy
General questions about SciPy
Basic SciPy/numpy usage
Advanced NumPy/SciPy usage
NumPy/SciPy installation
Miscellaneous Issues
Code documentation
The code is fairly well documented and you can quickly access a specific
command from within a python session:
>>> import numpy as np
>>> help(np.
An introduction to Numpy and Scipy
A short introduction to Numpy and Scipy by M. 1.. order='C')
Return a new array of given shape and type. filled with ones.
See Also
‐‐‐‐‐‐‐‐
zeros.core.numeric:
ones(shape. 1.])
http://www.. modules.
Numpy documentation
User guide
This guide is intended as an introductory overview of NumPy and explains how
to install and make use of the most important features of NumPy. ones_like
Examples
‐‐‐‐‐‐‐‐
>>> np.6/3/2015
Numpy tutorial
The Basics
Shape Manipulation
Copies and Views
Less Basic
Fancy indexing and index tricks
Linear Algebra
Tricks and Tips
Numpy MedKit
A first-aid kit for the numerically adventurous by Stéfan van der Walt. 1.ones(5)
array([ 1.labri.. Scott Shell. dtype=None. describing what they are and what they do.. and objects included in
Numpy.
Please refer to the documentation for `zeros` for further details.html
12/16
. 1.
Numpy reference
This reference manual details functions.ones)
Help on function ones in module numpy.