# Numpy - multidimensional data arrays¶

## Author: Steven Christe¶

Numpy is the fundamental library for scientific computing in Python. It contains list-like objects that work like arrays, matrices, and data tables. It also provides linear algebra, Fourier transforms, random number generation, and tools for integrating C/C++ and Fortran code.

Python was never designed originally for scientific computing, and contains many high-level abstractions necessary to enable its enormously flexible object-oriented interface. In Python, storing most integers requires more than just 4-8 bytes. It also requires at least a couple pointers per-integer. Performing a calculation on two numbers requires one or two bytecode operations, each of which can take dozens of CPU instructions for each pass through the Python eval loop. And when it comes to looping and index operations of Python lists the situation is even worst. NumPy provides efficient objects for dealing with arrays of numbers and overloads operators so you don't have to ever (hopefully) use loops!

This ipython notebook file can be found at

or can be viewed (if you don't have ipython installed) here

This is heavily cribbed from J.R. Johansson ([email protected]) http://dml.riken.jp/~rob/

The full version of the original talk is available at http://github.com/jrjohansson/scientific-python-lectures.

In :
%pylab inline

Populating the interactive namespace from numpy and matplotlib

WARNING: pylab import has clobbered these variables: ['indices']
%pylab --no-import-all prevents importing * from pylab and numpy

In :
import numpy as np

In :
import sys # only need to get python version
print("Python version: " + sys.version)
print("Numpy version: " + np.__version__)

Python version: 2.7.6 |Anaconda 1.8.0 (x86_64)| (default, Jan 10 2014, 11:23:15)
[GCC 4.0.1 (Apple Inc. build 5493)]
Numpy version: 1.8.1


In the numpy package the terminology used for vectors, matrices and higher-dimensional data sets is array.

## Creating numpy arrays¶

There are a number of ways to initialize new numpy arrays, for example from

• a Python list or tuples
• using functions that are dedicated to generating numpy arrays, such as arange, linspace, etc.

### From lists¶

For example, to create new vector and matrix arrays from Python lists we can use the numpy.array function.

In :
# a vector: the argument to the array function is a Python list
v = np.array([1,2,3,4])

v

Out:
array([1, 2, 3, 4])
In :
# a matrix: the argument to the array function is a nested Python list
M = np.array([[1, 6], [3, 4]])

M

Out:
array([[1, 6],
[3, 4]])

The v and M objects are both of the type ndarray that the numpy module provides.

In :
type(v), type(M)

Out:
(numpy.ndarray, numpy.ndarray)

The difference between the v and M arrays is only their shapes. We can get information about the shape of an array by using the ndarray.shape property.

In :
v.shape

Out:
(4,)
In :
M.shape

Out:
(2, 2)

The number of elements in the array is available through the ndarray.size property:

In :
M.size

Out:
4

Equivalently, we could use the function numpy.shape and numpy.size

In :
np.shape(M)

Out:
(2, 2)
In :
np.size(M)

Out:
4

Features of a numpy.ndarray

• Numpy arrays are statically typed and homogeneous. The type of the elements is determined when array is created.
• Numpy arrays are memory efficient.
• Because of the static typing, fast implementation of mathematical functions such as multiplication and addition of numpy arrays can be implemented in a compiled language (C and Fortran is used).

Using the dtype (data type) property of an ndarray, we can see what type the data of an array has:

In :
M.dtype

Out:
dtype('int64')

We get an error if we try to assign a value of the wrong type to an element in a numpy array:

If we want, we can explicitly define the type of the array data when we create it, using the dtype keyword argument:

In :
M = np.array([[1, 2], [3, 4]], dtype=np.float16)

M

Out:
array([[ 1.,  2.],
[ 3.,  4.]], dtype=float16)

Common type that can be used with dtype are: int, float, complex, bool, object, etc.

### Array-generating functions¶

For larger arrays it is inpractical to initialize the data manually, using explicit python lists. Instead we can use one of the many functions in numpy that generates arrays of different forms. Some of the more common are:

#### arange¶

In :
# create a range

x = np.arange(0, 10, 1) # arguments: start, stop, step

x

Out:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In :
x = np.arange(-1, 1, 0.1)

x

Out:
array([ -1.00000000e+00,  -9.00000000e-01,  -8.00000000e-01,
-7.00000000e-01,  -6.00000000e-01,  -5.00000000e-01,
-4.00000000e-01,  -3.00000000e-01,  -2.00000000e-01,
-1.00000000e-01,  -2.22044605e-16,   1.00000000e-01,
2.00000000e-01,   3.00000000e-01,   4.00000000e-01,
5.00000000e-01,   6.00000000e-01,   7.00000000e-01,
8.00000000e-01,   9.00000000e-01])

#### linspace and logspace¶

In :
# using linspace, both end points ARE included
np.linspace(0, 10, 25)

Out:
array([  0.        ,   0.41666667,   0.83333333,   1.25      ,
1.66666667,   2.08333333,   2.5       ,   2.91666667,
3.33333333,   3.75      ,   4.16666667,   4.58333333,
5.        ,   5.41666667,   5.83333333,   6.25      ,
6.66666667,   7.08333333,   7.5       ,   7.91666667,
8.33333333,   8.75      ,   9.16666667,   9.58333333,  10.        ])
In :
np.logspace(0, 10, 10, base=e)

Out:
array([  1.00000000e+00,   3.03773178e+00,   9.22781435e+00,
2.80316249e+01,   8.51525577e+01,   2.58670631e+02,
7.85771994e+02,   2.38696456e+03,   7.25095809e+03,
2.20264658e+04])

#### mgrid¶

In :
x, y = np.mgrid[0:5, 0:5] # similar to meshgrid in MATLAB

In :
x

Out:
array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4]])
In :
y

Out:
array([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])

#### random data¶

In :
from numpy import random

In :
# uniform random numbers in [0,1]
random.rand(5,5)

Out:
array([[ 0.32846187,  0.42213273,  0.01968231,  0.21261055,  0.51482732],
[ 0.08183575,  0.00824206,  0.62834203,  0.77968281,  0.126293  ],
[ 0.38743163,  0.86545303,  0.40312758,  0.8053914 ,  0.48047428],
[ 0.61395831,  0.89044911,  0.14621425,  0.48195724,  0.38045612],
[ 0.20086805,  0.27765159,  0.08753675,  0.18159165,  0.64932571]])
In :
# standard normal distributed random numbers
random.randn(5,5)

Out:
array([[-0.78404982, -0.57134026,  1.49107161, -1.26857542,  0.44456653],
[-0.02629558,  0.08901156, -1.08758579,  0.22911653, -1.98229464],
[ 0.33490693,  0.65502718,  0.23791072, -0.22042591, -0.01485002],
[ 1.49117271, -0.76377386,  0.54285327, -0.78657823,  1.72420386],
[ 1.77250365, -1.02862661,  0.07318933, -0.06165841, -1.93811428]])

#### zeros and ones¶

In :
np.zeros((3,3))

Out:
array([[ 0.,  0.,  0.],
[ 0.,  0.,  0.],
[ 0.,  0.,  0.]])
In :
np.ones((3,3))

Out:
array([[ 1.,  1.,  1.],
[ 1.,  1.,  1.],
[ 1.,  1.,  1.]])

## More properties of the numpy arrays¶

In :
M.itemsize # bytes per element

Out:
2
In :
M.nbytes # number of bytes

Out:
8
In :
M.ndim # number of dimensions

Out:
2

## Manipulating arrays¶

### Indexing¶

We can index elements in an array using the square bracket and indices:

In :
# v is a vector, and has only one dimension, taking one index
v

Out:
1
In :
# M is a matrix, or a 2 dimensional array, taking two indices
M[1,1]

Out:
4.0

The same thing can be achieved with using : instead of an index:

In :
M[1,:] # row 1

Out:
array([ 3.,  4.], dtype=float16)
In :
M[:,1] # column 1

Out:
array([ 2.,  4.], dtype=float16)

We can assign new values to elements in an array using indexing:

In :
M[0,0] = 1

In :
M

Out:
array([[ 1.,  2.],
[ 3.,  4.]], dtype=float16)
In :
# also works for rows and columns
M[1,:] = 0
M[:,1] = -1

In :
M

Out:
array([[ 1., -1.],
[ 0., -1.]], dtype=float16)

### Index slicing¶

Index slicing is the technical name for the syntax M[lower:upper:step] to extract part of an array:

In :
A = np.array([1,2,3,4,5])
A

Out:
array([1, 2, 3, 4, 5])
In :
A[1:3]

Out:
array([2, 3])

Array slices are mutable: if they are assigned a new value the original array from which the slice was extracted is modified:

In :
A[1:3] = [-2,-3]

A

Out:
array([ 1, -2, -3,  4,  5])

We can omit any of the three parameters in M[lower:upper:step]:

In :
A[::] # lower, upper, step all take the default values

Out:
array([ 1, -2, -3,  4,  5])
In :
A[::2] # step is 2, lower and upper defaults to the beginning and end of the array

Out:
array([ 1, -3,  5])
In :
A[:3] # first three elements

Out:
array([ 1, -2, -3])
In :
A[3:] # elements from index 3

Out:
array([4, 5])

Negative indices counts from the end of the array (positive index from the begining):

In :
A = np.array([1,2,3,4,5])

In :
A[-1] # the last element in the array

Out:
5
In :
A[-3:] # the last three elements

Out:
array([3, 4, 5])

Index slicing works exactly the same way for multidimensional arrays:

In :
A = np.array([[n+m*10 for n in range(5)] for m in range(5)])

A

Out:
array([[ 0,  1,  2,  3,  4],
[10, 11, 12, 13, 14],
[20, 21, 22, 23, 24],
[30, 31, 32, 33, 34],
[40, 41, 42, 43, 44]])
In :
# a block from the original array
A[1:4, 1:4]

Out:
array([[11, 12, 13],
[21, 22, 23],
[31, 32, 33]])
In :
# strides
A[::2, ::2]

Out:
array([[ 0,  2,  4],
[20, 22, 24],
[40, 42, 44]])
In :
A

Out:
array([3, 4])

### Fancy indexing¶

Fancy indexing is the name for when an array or list is used in-place of an index:

In :
row_indices = [1, 2, 3]
A[row_indices]

Out:
array([[10, 11, 12, 13, 14],
[20, 21, 22, 23, 24],
[30, 31, 32, 33, 34]])
In :
col_indices = [1, 2, -1] # remember, index -1 means the last element
A[row_indices, col_indices]

Out:
array([11, 22, 34])

We can also index masks: If the index mask is an Numpy array of with data type bool, then an element is selected (True) or not (False) depending on the value of the index mask at the position each element:

In :
B = array([n for n in range(5)])
B

Out:
array([0, 1, 2, 3, 4])
In :
row_mask = array([True, False, True, False, False])

Out:
array([0, 2])
In :
# same thing

Out:
array([0, 2])

This feature is very useful to conditionally select elements from an array, using for example comparison operators:

In :
x = np.arange(0, 10, 0.5)
x

Out:
array([ 0. ,  0.5,  1. ,  1.5,  2. ,  2.5,  3. ,  3.5,  4. ,  4.5,  5. ,
5.5,  6. ,  6.5,  7. ,  7.5,  8. ,  8.5,  9. ,  9.5])
In :
mask = (5 < x) * (x < 7.5)


Out:
array([False, False, False, False, False, False, False, False, False,
False, False,  True,  True,  True,  True, False, False, False,
False, False], dtype=bool)
In :
x[mask]

Out:
array([ 5.5,  6. ,  6.5,  7. ])

## Functions for extracting data from arrays and creating arrays¶

### where¶

The index mask can be converted to position index using the where function

In :
indices = np.where(mask)

indices

Out:
(array([11, 12, 13, 14]),)
In :
x[indices] # this indexing is equivalent to the fancy indexing x[mask]

Out:
array([ 5.5,  6. ,  6.5,  7. ])

### diag¶

With the diag function we can also extract the diagonal and subdiagonals of an array:

In :
np.diag(A)

Out:
array([ 0, 11, 22, 33, 44])
In :
np.diag(A, -1)

Out:
array([10, 21, 32, 43])

### take¶

The take function is similar to fancy indexing described above:

In :
v2 = np.arange(-3,3)
v2

Out:
array([-3, -2, -1,  0,  1,  2])
In :
row_indices = [1, 3, 5]
v2[row_indices] # fancy indexing

Out:
array([-2,  0,  2])
In :
v2.take(row_indices)

Out:
array([-2,  0,  2])

But take also works on lists and other objects:

In :
np.take([-3, -2, -1,  0,  1,  2], row_indices)

Out:
array([-2,  0,  2])

### choose¶

Constructs and array by picking elements form several arrays:

In :
which = [1, 0, 1, 0]
choices = [[-2,-2,-2,-2], [5,5,5,5]]

np.choose(which, choices)

Out:
array([ 5, -2,  5, -2])

## Linear algebra¶

Vectorizing code is the key to writing efficient numerical calculation with Python/Numpy. That means that as much as possible of a program should be formulated in terms of matrix and vector operations, like matrix-matrix multiplication.

### Scalar-array operations¶

We can use the usual arithmetic operators to multiply, add, subtract, and divide arrays with scalar numbers.

In :
v1 = np.arange(0, 5)

In :
v1 * 2

Out:
array([0, 2, 4, 6, 8])
In :
v1 + 2

Out:
array([2, 3, 4, 5, 6])
In :
A * 2, A + 2

Out:
(array([[ 0,  2,  4,  6,  8],
[20, 22, 24, 26, 28],
[40, 42, 44, 46, 48],
[60, 62, 64, 66, 68],
[80, 82, 84, 86, 88]]),
array([[ 2,  3,  4,  5,  6],
[12, 13, 14, 15, 16],
[22, 23, 24, 25, 26],
[32, 33, 34, 35, 36],
[42, 43, 44, 45, 46]]))

### Element-wise array-array operations¶

When we add, subtract, multiply and divide arrays with each other, the default behaviour is element-wise operations:

In :
A * A # element-wise multiplication

Out:
array([[   0,    1,    4,    9,   16],
[ 100,  121,  144,  169,  196],
[ 400,  441,  484,  529,  576],
[ 900,  961, 1024, 1089, 1156],
[1600, 1681, 1764, 1849, 1936]])
In :
v1 * v1

Out:
array([ 0,  1,  4,  9, 16])

If we multiply arrays with compatible shapes, we get an element-wise multiplication of each row:

In :
A.shape, v1.shape

Out:
((5, 5), (5,))
In :
A * v1

Out:
array([[  0,   1,   4,   9,  16],
[  0,  11,  24,  39,  56],
[  0,  21,  44,  69,  96],
[  0,  31,  64,  99, 136],
[  0,  41,  84, 129, 176]])

### Matrix algebra¶

What about matrix mutiplication? There are two ways. We can either use the dot function, which applies a matrix-matrix, matrix-vector, or inner vector multiplication to its two arguments:

In :
np.dot(A, A)

Out:
array([[ 300,  310,  320,  330,  340],
[1300, 1360, 1420, 1480, 1540],
[2300, 2410, 2520, 2630, 2740],
[3300, 3460, 3620, 3780, 3940],
[4300, 4510, 4720, 4930, 5140]])
In :
np.dot(A, v1)

Out:
array([ 30, 130, 230, 330, 430])
In :
np.dot(v1, v1)

Out:
30

Alternatively, we can cast the array objects to the type matrix. This changes the behavior of the standard arithmetic operators +, -, * to use matrix algebra.

In :
M = np.matrix(A)
v = np.matrix(v1).T # make it a column vector

In :
v

Out:
matrix([,
,
,
,
])
In :
M * M

Out:
matrix([[ 300,  310,  320,  330,  340],
[1300, 1360, 1420, 1480, 1540],
[2300, 2410, 2520, 2630, 2740],
[3300, 3460, 3620, 3780, 3940],
[4300, 4510, 4720, 4930, 5140]])
In :
M * v

Out:
matrix([[ 30],
,
,
,
])
In :
# inner product
v.T * v

Out:
matrix([])
In :
# with matrix objects, standard matrix algebra applies
v + M*v

Out:
matrix([[ 30],
,
,
,
])

If we try to add, subtract or multiply objects with incomplatible shapes we get an error:

In :
v = np.matrix([1,2,3,4,5,6]).T

In :
shape(M), shape(v)

Out:
((5, 5), (6, 1))
In :
M * v

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
----> 1 M * v

/Users/schriste/anaconda/lib/python2.7/site-packages/numpy/matrixlib/defmatrix.pyc in __mul__(self, other)
328         if isinstance(other,(N.ndarray, list, tuple)) :
329             # This promotes 1-D vectors to row vectors
--> 330             return N.dot(self, asmatrix(other))
331         if isscalar(other) or not hasattr(other, '__rmul__') :
332             return N.dot(self, other)

ValueError: objects are not aligned

See also the related functions: inner, outer, cross, kron, tensordot. Try for example help(kron).

### Array/Matrix transformations¶

Above we have used the .T to transpose the matrix object v. We could also have used the transpose function to accomplish the same thing.

Other mathematical functions that transforms matrix objects are:

In [ ]:
C = np.matrix([[1j, 2j], [3j, 4j]])
C

In :
np.conjugate(C)

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-86-934f2dd5e2ef> in <module>()
----> 1 np.conjugate(C)

NameError: name 'C' is not defined

Hermitian conjugate: transpose + conjugate

In :
C.H

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-87-bdd18b98227d> in <module>()
----> 1 C.H

NameError: name 'C' is not defined

We can extract the real and imaginary parts of complex-valued arrays using real and imag:

In :
np.real(C) # same as: C.real

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-88-b672483d4bc4> in <module>()
----> 1 np.real(C) # same as: C.real

NameError: name 'C' is not defined
In :
np.imag(C) # same as: C.imag

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-89-1ed1d19d3c2c> in <module>()
----> 1 np.imag(C) # same as: C.imag

NameError: name 'C' is not defined

Or the complex argument and absolute value

In :
np.angle(C+1) # heads up MATLAB Users, angle is used instead of arg

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-90-3775d8ef0c87> in <module>()
----> 1 np.angle(C+1) # heads up MATLAB Users, angle is used instead of arg

NameError: name 'C' is not defined
In :
np.abs(C)

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-91-56f6751545e7> in <module>()
----> 1 np.abs(C)

NameError: name 'C' is not defined

### Matrix computations¶

#### Inverse¶

In :
inv(C) # equivalent to C.I

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-92-0b30bd464f9b> in <module>()
----> 1 inv(C) # equivalent to C.I

NameError: name 'C' is not defined
In :
C.I * C

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-93-33ab9fba3975> in <module>()
----> 1 C.I * C

NameError: name 'C' is not defined

#### Determinant¶

In [ ]:
det(C)

In [ ]:
det(C.I)


#### sum, prod, and trace¶

In [ ]:
d = arange(0, 10)
d

In [ ]:
# sum up all elements
sum(d)

In :
# product of all elements
prod(d+1)

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-94-e8cd400f9a6b> in <module>()
1 # product of all elements
----> 2 prod(d+1)

NameError: name 'd' is not defined
In :
# cummulative sum
cumsum(d)

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-95-242a18f7884c> in <module>()
1 # cummulative sum
----> 2 cumsum(d)

NameError: name 'd' is not defined
In :
# cummulative product
cumprod(d+1)

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-96-bcb7dc412ffa> in <module>()
1 # cummulative product
----> 2 cumprod(d+1)

NameError: name 'd' is not defined
In :
# same as: diag(A).sum()
trace(A)

Out:
110

### Calculations with higher-dimensional data¶

When functions such as min, max, etc., is applied to a multidimensional arrays, it is sometimes useful to apply the calculation to the entire array, and sometimes only on a row or column basis. Using the axis argument we can specify how these functions should behave:

In :
m = rand(3,3)
m

Out:
array([[ 0.45974672,  0.90724345,  0.23833268],
[ 0.90236963,  0.51838115,  0.64488138],
[ 0.49125775,  0.50524105,  0.3813743 ]])
In :
# global max
m.max()

Out:
0.90724344539482737
In :
# max in each column
m.max(axis=0)

Out:
array([ 0.90236963,  0.90724345,  0.64488138])
In :
# max in each row
m.max(axis=1)

Out:
array([ 0.90724345,  0.90236963,  0.50524105])

Many other functions and methods in the array and matrix classes accept the same (optional) axis keyword argument.

## Reshaping, resizing and stacking arrays¶

The shape of an Numpy array can be modified without copying the underlaying data, which makes it a fast operation even for large arrays.

In :
A

Out:
array([[ 0,  1,  2,  3,  4],
[10, 11, 12, 13, 14],
[20, 21, 22, 23, 24],
[30, 31, 32, 33, 34],
[40, 41, 42, 43, 44]])
In :
n, m = A.shape

In :
B = A.reshape((1,n*m))
B

Out:
array([[ 0,  1,  2,  3,  4, 10, 11, 12, 13, 14, 20, 21, 22, 23, 24, 30, 31,
32, 33, 34, 40, 41, 42, 43, 44]])
In :
B[0,0:5] = 5 # modify the array

B

Out:
array([[ 5,  5,  5,  5,  5, 10, 11, 12, 13, 14, 20, 21, 22, 23, 24, 30, 31,
32, 33, 34, 40, 41, 42, 43, 44]])
In :
A # and the original variable is also changed. B is only a different view of the same data

Out:
array([[ 5,  5,  5,  5,  5],
[10, 11, 12, 13, 14],
[20, 21, 22, 23, 24],
[30, 31, 32, 33, 34],
[40, 41, 42, 43, 44]])

We can also use the function flatten to make a higher-dimensional array into a vector. But this function create a copy of the data.

In :
B = A.flatten()

B

Out:
array([ 5,  5,  5,  5,  5, 10, 11, 12, 13, 14, 20, 21, 22, 23, 24, 30, 31,
32, 33, 34, 40, 41, 42, 43, 44])
In :
B[0:5] = 10

B

Out:
array([10, 10, 10, 10, 10, 10, 11, 12, 13, 14, 20, 21, 22, 23, 24, 30, 31,
32, 33, 34, 40, 41, 42, 43, 44])
In :
A # now A has not changed, because B's data is a copy of A's, not refering to the same data

Out:
array([[ 5,  5,  5,  5,  5],
[10, 11, 12, 13, 14],
[20, 21, 22, 23, 24],
[30, 31, 32, 33, 34],
[40, 41, 42, 43, 44]])

## Adding a new dimension: newaxis¶

With newaxis, we can insert new dimensions in an array, for example converting a vector to a column or row matrix:

In :
v = np.array([1,2,3])

In :
np.shape(v)

Out:
(3,)
In :
# make a column matrix of the vector v
v[:, newaxis]

Out:
array([,
,
])
In :
# column matrix
v[:,newaxis].shape

Out:
(3, 1)
In :
# row matrix
v[newaxis,:].shape

Out:
(1, 3)

## Stacking and repeating arrays¶

Using function repeat, tile, vstack, hstack, and concatenate we can create larger vectors and matrices from smaller ones:

### tile and repeat¶

In :
a = np.array([[1, 2], [3, 4]])

In :
# repeat each element 3 times
np.repeat(a, 3)

Out:
array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4])
In :
# tile the matrix 3 times
np.tile(a, 3)

Out:
array([[1, 2, 1, 2, 1, 2],
[3, 4, 3, 4, 3, 4]])

### concatenate¶

In :
b = np.array([[5, 6]])

In :
np.concatenate((a, b), axis=0)

Out:
array([[1, 2],
[3, 4],
[5, 6]])
In :
np.concatenate((a, b.T), axis=1)

Out:
array([[1, 2, 5],
[3, 4, 6]])

### hstack and vstack¶

In :
np.vstack((a,b))

Out:
array([[1, 2],
[3, 4],
[5, 6]])
In :
np.hstack((a,b.T))

Out:
array([[1, 2, 5],
[3, 4, 6]])

## Copy and "deep copy"¶

To achieve high performance, assignments in Python usually do not copy the underlaying objects. This is important for example when objects are passed between functions, to avoid an excessive amount of memory copying when it is not necessary (techincal term: pass by reference).

In :
A = np.array([[1, 2], [3, 4]])

A

Out:
array([[1, 2],
[3, 4]])
In :
# now B is referring to the same array data as A
B = A

In :
# changing B affects A
B[0,0] = 10

B

Out:
array([[10,  2],
[ 3,  4]])
In :
A

Out:
array([[10,  2],
[ 3,  4]])

If we want to avoid this behavior, so that when we get a new completely independent object B copied from A, then we need to do a so-called "deep copy" using the function copy:

In :
B = copy(A)

In :
# now, if we modify B, A is not affected
B[0,0] = -5

B

Out:
array([[-5,  2],
[ 3,  4]])
In :
A

Out:
array([[10,  2],
[ 3,  4]])

## Iterating over array elements¶

Generally, we want to avoid iterating over the elements of arrays whenever we can (at all costs). The reason is that in a interpreted language like Python (or MATLAB), iterations are really slow compared to vectorized operations.

However, sometimes iterations are unavoidable. For such cases, the Python for loop is the most convenient way to iterate over an array:

In :
v = np.array([1,2,3,4])

for element in v:
print(element)

1
2
3
4

In :
M = np.array([[1,2], [3,4]])

for row in M:
print("row", row)

for element in row:
print(element)

('row', array([1, 2]))
1
2
('row', array([3, 4]))
3
4


When we need to iterate over each element of an array and modify its elements, it is convenient to use the enumerate function to obtain both the element and its index in the for loop:

In :
for row_idx, row in enumerate(M):
print("row_idx", row_idx, "row", row)

for col_idx, element in enumerate(row):
print("col_idx", col_idx, "element", element)

# update the matrix M: square each element
M[row_idx, col_idx] = element ** 2

('row_idx', 0, 'row', array([1, 2]))
('col_idx', 0, 'element', 1)
('col_idx', 1, 'element', 2)
('row_idx', 1, 'row', array([3, 4]))
('col_idx', 0, 'element', 3)
('col_idx', 1, 'element', 4)

In :
# each element in M is now squared
M

Out:
array([[ 1,  4],
[ 9, 16]])

## Vectorizing functions¶

As mentioned several times by now, to get good performance we should try to avoid looping over elements in our vectors and matrices, and instead use vectorized algorithms. The first step in converting a scalar algorithm to a vectorized algorithm is to make sure that the functions we write work with vector inputs.

In :
def Theta(x):
"""
Scalar implemenation of the Heaviside step function.
"""
if x >= 0:
return 1
else:
return 0

In :
Theta(np.array([-3,-2,-1,0,1,2,3]))

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-135-d55419725688> in <module>()
----> 1 Theta(np.array([-3,-2,-1,0,1,2,3]))

<ipython-input-134-9a0cb13d93d4> in Theta(x)
3     Scalar implemenation of the Heaviside step function.
4     """
----> 5     if x >= 0:
6         return 1
7     else:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

OK, that didn't work because we didn't write the Theta function so that it can handle with vector input...

To get a vectorized version of Theta we can use the Numpy function vectorize. In many cases it can automatically vectorize a function:

In :
Theta_vec = np.vectorize(Theta)

In :
Theta_vec(np.array([-3,-2,-1,0,1,2,3]))

Out:
array([0, 0, 0, 1, 1, 1, 1])

We can also implement the function to accept vector input from the beginning (requires more effort but might give better performance):

In :
def Theta(x):
"""
Vector-aware implemenation of the Heaviside step function.
"""
return 1 * (x >= 0)

In :
Theta(np.array([-3,-2,-1,0,1,2,3]))

Out:
array([0, 0, 0, 1, 1, 1, 1])
In :
# still works for scalars as well
Theta(-1.2), Theta(2.6)

Out:
(0, 1)

## Using arrays in conditions¶

When using arrays in conditions in for example if statements and other boolean expressions, one need to use one of any or all, which requires that any or all elements in the array evalutes to True:

In :
M

Out:
array([[ 1,  4],
[ 9, 16]])
In :
if (M > 5).any():
print("at least one element in M is larger than 5")
else:
print("no element in M is larger than 5")

at least one element in M is larger than 5

In :
if (M > 5).all():
print("all elements in M are larger than 5")
else:
print("all elements in M are not larger than 5")

all elements in M are not larger than 5


## Type casting¶

Since Numpy arrays are statically typed, the type of an array does not change once created. But we can explicitly cast an array of some type to another using the astype functions (see also the similar asarray function). This always create a new array of new type:

In :
M.dtype

Out:
dtype('int64')
In :
M2 = M.astype(float)

M2

Out:
array([[  1.,   4.],
[  9.,  16.]])
In :
M2.dtype

Out:
dtype('float64')
In :
M3 = M.astype(bool)

M3

Out:
array([[ True,  True],
[ True,  True]], dtype=bool)

# SciPy¶

In :