Numpy - multidimensional data arrays


In [ ]:

Introduction

The numpy package (module) is used in almost all numerical computation using Python. It is a package that provide high-performance vector, matrix and higher-dimensional data structures for Python. It is implemented in C and Fortran so when calculations are vectorized (formulated with vectors and matrices), performance is very good.

To use numpy you need to import the module, using for example:


In [1]:
import numpy as np

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.
  • reading data from files

From lists

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


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

v


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

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

M


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

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


In [5]:
type(v), type(M)


Out[5]:
(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 [6]:
v.shape


Out[6]:
(4,)

In [7]:
M.shape


Out[7]:
(2, 2)

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


In [8]:
M.size


Out[8]:
4

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


In [10]:
np.shape(M)


Out[10]:
(2, 2)

In [11]:
np.size(M)


Out[11]:
4

So far the numpy.ndarray looks awefully much like a Python list (or nested list). Why not simply use Python lists for computations instead of creating a new array type?

There are several reasons:

  • Python lists are very general. They can contain any kind of object. They are dynamically typed. They do not support mathematical functions such as matrix and dot multiplications, etc. Implementing such functions for Python lists would not be very efficient because of the dynamic typing.
  • Numpy arrays are statically typed and homogeneous. The type of the elements is determined when the 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 [12]:
M.dtype


Out[12]:
dtype('int64')

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


In [13]:
M[0,0] = "hello"


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-13-a09d72434238> in <module>()
----> 1 M[0,0] = "hello"

ValueError: invalid literal for long() with base 10: 'hello'

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


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

M


Out[14]:
array([[ 1.+0.j,  2.+0.j],
       [ 3.+0.j,  4.+0.j]])

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

We can also explicitly define the bit size of the data types, for example: int64, int16, float128, complex128.

Using 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 generate arrays of different forms. Some of the more common are:

arange


In [15]:
# create a range

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

x


Out[15]:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [16]:
x = np.arange(-1, 1, 0.1)

x


Out[16]:
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 [17]:
# using linspace, both end points ARE included
np.linspace(0, 10, 25)


Out[17]:
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 [19]:
np.logspace(0, 10, 10, base=np.e)


Out[19]:
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 [20]:
x, y = np.mgrid[0:5, 0:5] # similar to meshgrid in MATLAB

In [21]:
x


Out[21]:
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 [22]:
y


Out[22]:
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 [27]:
from numpy import random

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


Out[28]:
array([[ 0.49406293,  0.21425745,  0.61331193,  0.32784842,  0.99591338],
       [ 0.24089539,  0.44805359,  0.09345322,  0.56656295,  0.44791492],
       [ 0.13505864,  0.88682905,  0.00324599,  0.74313305,  0.50196652],
       [ 0.09585222,  0.26228338,  0.02996983,  0.32233701,  0.30819306],
       [ 0.77678822,  0.77188318,  0.81466163,  0.01803531,  0.96661312]])

In [29]:
# standard normal distributed random numbers
random.randn(5,5)


Out[29]:
array([[-1.24588781, -0.5974331 , -0.40903861,  1.2327517 ,  0.51265757],
       [-0.9178861 ,  0.75621978, -0.11977446,  0.67184885,  1.21928622],
       [ 0.29441652, -0.43413505,  0.97153403,  0.14295138, -0.30659839],
       [-0.37641243, -1.200776  , -0.97160933,  0.56522347, -1.31024933],
       [-0.05640364,  0.28085847,  0.94445629,  0.53184511, -1.74751539]])

diag


In [30]:
# a diagonal matrix
np.diag([1,2,3])


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

In [31]:
# diagonal with offset from the main diagonal
np.diag([1,2,3], k=1)


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

zeros and ones


In [91]:
np.zeros((3,3))


Out[91]:
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])

In [92]:
np.ones((3,3))


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

File I/O

Comma-separated values (CSV)

A very common file format for data files is comma-separated values (CSV), or related formats such as TSV (tab-separated values). To read data from such files into Numpy arrays we can use the numpy.genfromtxt function. For example,


In [93]:
%%bash
echo '
1800  1  1    -6.1    -6.1    -6.1 1
1800  1  2   -15.4   -15.4   -15.4 1
1800  1  3   -15.0   -15.0   -15.0 1
1800  1  4   -19.3   -19.3   -19.3 1
1800  1  5   -16.8   -16.8   -16.8 1
1800  1  6   -11.4   -11.4   -11.4 1
1800  1  7    -7.6    -7.6    -7.6 1
1800  1  8    -7.1    -7.1    -7.1 1
1800  1  9   -10.1   -10.1   -10.1 1
1800  1 10    -9.5    -9.5    -9.5 1
' > test.dat

In [94]:
data = np.genfromtxt('test.dat')

In [95]:
data.shape


Out[95]:
(10, 7)

In [96]:
print data[:,0]
print data[0,:]


[ 1800.  1800.  1800.  1800.  1800.  1800.  1800.  1800.  1800.  1800.]
[  1.80000000e+03   1.00000000e+00   1.00000000e+00  -6.10000000e+00
  -6.10000000e+00  -6.10000000e+00   1.00000000e+00]

Using numpy.savetxt we can store a Numpy array to a file in CSV format:


In [97]:
M = random.rand(3,3)

M


Out[97]:
array([[ 0.56592074,  0.31925451,  0.07071436],
       [ 0.40445531,  0.33905924,  0.06890646],
       [ 0.43876792,  0.11784734,  0.80457052]])

In [98]:
np.savetxt("random-matrix.csv", M)

In [99]:
!cat random-matrix.csv


5.659207388768656699e-01 3.192545105089277246e-01 7.071436311328971325e-02
4.044553055396516994e-01 3.390592443226384534e-01 6.890646403468136949e-02
4.387679159929198658e-01 1.178473431220541379e-01 8.045705234897031488e-01

In [100]:
np.savetxt("random-matrix.csv", M, fmt='%.5f') # fmt specifies the format

!cat random-matrix.csv


0.56592 0.31925 0.07071
0.40446 0.33906 0.06891
0.43877 0.11785 0.80457

In [101]:
A = np.loadtxt("random-matrix.csv")
print A


[[ 0.56592  0.31925  0.07071]
 [ 0.40446  0.33906  0.06891]
 [ 0.43877  0.11785  0.80457]]

loadtxt can read directly from gzipped (.gz) and bzip2 (.bz2) files.

More complicate files can be read using more options. For instance, to read a file skipping all comment lines (starting with a #) and the first 5 rows, reading only in columns 0,1,2 using a comma as delimiter we give the command:

array = np.loadtxt(filename, dtype=dtype, comments=‘#’, delimiter=‘,’, skiprows=5, usecols=(0, 1, 2))

Numpy's native file format

Useful when storing and reading back numpy array data. Use the functions numpy.save and numpy.load:


In [102]:
np.save("random-matrix.npy", M)
!file random-matrix.npy


random-matrix.npy: data

In [103]:
np.load("random-matrix.npy")


Out[103]:
array([[ 0.56592074,  0.31925451,  0.07071436],
       [ 0.40445531,  0.33905924,  0.06890646],
       [ 0.43876792,  0.11784734,  0.80457052]])

More properties of the numpy arrays


In [104]:
M.itemsize # bytes per element


Out[104]:
8

In [105]:
M.nbytes # number of bytes


Out[105]:
72

In [106]:
M.ndim # number of dimensions


Out[106]:
2

Manipulating arrays

Indexing

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


In [107]:
# v is a vector, and has only one dimension, taking one index
v[0]


Out[107]:
1

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


Out[108]:
0.33905924432263845

If we omit an index of a multidimensional array it returns the whole row (or, in general, a N-1 dimensional array)


In [109]:
M


Out[109]:
array([[ 0.56592074,  0.31925451,  0.07071436],
       [ 0.40445531,  0.33905924,  0.06890646],
       [ 0.43876792,  0.11784734,  0.80457052]])

In [110]:
M[1]


Out[110]:
array([ 0.40445531,  0.33905924,  0.06890646])

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


In [111]:
M[1,:] # row 1


Out[111]:
array([ 0.40445531,  0.33905924,  0.06890646])

In [112]:
M[:,1] # column 1


Out[112]:
array([ 0.31925451,  0.33905924,  0.11784734])

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


In [113]:
M[0,0] = 1

In [114]:
M


Out[114]:
array([[ 1.        ,  0.31925451,  0.07071436],
       [ 0.40445531,  0.33905924,  0.06890646],
       [ 0.43876792,  0.11784734,  0.80457052]])

In [115]:
# also works for rows and columns
M[1,:] = 0
M[:,2] = -1

In [116]:
M


Out[116]:
array([[ 1.        ,  0.31925451, -1.        ],
       [ 0.        ,  0.        , -1.        ],
       [ 0.43876792,  0.11784734, -1.        ]])

Index slicing

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


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


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

In [119]:
A[1:3]


Out[119]:
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 [120]:
A[1:3] = [-2,-3]

A


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

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


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


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

In [122]:
A[::2] # step is 2, lower and upper defaults to the beginning and end of the array


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

In [123]:
A[:3] # first three elements


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

In [124]:
A[3:] # elements from index 3


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

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


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

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


Out[126]:
5

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


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

Index slicing works exactly the same way for multidimensional arrays:


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

A


Out[128]:
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 [129]:
# a block from the original array
A[1:4, 1:4]


Out[129]:
array([[11, 12, 13],
       [21, 22, 23],
       [31, 32, 33]])

In [130]:
# strides
A[::2, ::2]


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

Fancy indexing

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


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


Out[131]:
array([[10, 11, 12, 13, 14],
       [20, 21, 22, 23, 24],
       [30, 31, 32, 33, 34]])

In [132]:
col_indices = [1, 2, -1] # remember, index -1 means the last element
A[row_indices, col_indices]


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

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


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


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

In [134]:
row_mask = np.array([True, False, True, False, False])
B[row_mask]


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

In [135]:
# same thing
row_mask = np.array([1,0,1,0,0], dtype=bool)
B[row_mask]


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

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


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


Out[136]:
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 [137]:
mask = (5 < x) * (x < 7.5)

mask


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

In [138]:
x[mask]


Out[138]:
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 [139]:
indices = np.where(mask)

indices


Out[139]:
(array([11, 12, 13, 14]),)

In [140]:
x[indices] # this indexing is equivalent to the fancy indexing x[mask]


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

diag

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


In [141]:
np.diag(A)


Out[141]:
array([ 0, 11, 22, 33, 44])

In [142]:
np.diag(A, -1)


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

take

The take function is similar to fancy indexing described above:


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


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

In [144]:
row_indices = [1, 3, 5]
v2[row_indices] # fancy indexing


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

In [78]:
v2.take(row_indices)


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

But take also works on lists and other objects:


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


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

choose

Constructs an array by picking elements from several arrays:


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

np.choose(which, choices)


Out[147]:
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 [148]:
v1 = np.arange(0, 5)

In [149]:
v1 * 2


Out[149]:
array([0, 2, 4, 6, 8])

In [150]:
v1 + 2


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

In [158]:
print "A*2 ",A * 2
print "A+2 ",A + 2


A*2  [[ 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]]
A+2  [[ 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 [159]:
A * A # element-wise multiplication


Out[159]:
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 [160]:
v1 * v1


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

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


In [161]:
A.shape, v1.shape


Out[161]:
((5, 5), (5,))

In [162]:
A * v1


Out[162]:
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 [163]:
np.dot(A, A)


Out[163]:
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 [164]:
np.dot(A, v1)


Out[164]:
array([ 30, 130, 230, 330, 430])

In [165]:
np.dot(v1, v1)


Out[165]:
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 [166]:
M = np.matrix(A)
v = np.matrix(v1).T # make it a column vector

In [167]:
v


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

In [168]:
M * M


Out[168]:
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 [169]:
M * v


Out[169]:
matrix([[ 30],
        [130],
        [230],
        [330],
        [430]])

In [170]:
# inner product
v.T * v


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

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


Out[171]:
matrix([[ 30],
        [131],
        [232],
        [333],
        [434]])

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


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

In [173]:
M.shape, v.shape


Out[173]:
((5, 5), (6, 1))

In [174]:
M * v


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-174-995fb48ad0cc> in <module>()
----> 1 M * v

/home/dario/anaconda/lib/python2.7/site-packages/numpy/matrixlib/defmatrix.pyc in __mul__(self, other)
    341         if isinstance(other, (N.ndarray, list, tuple)) :
    342             # This promotes 1-D vectors to row vectors
--> 343             return N.dot(self, asmatrix(other))
    344         if isscalar(other) or not hasattr(other, '__rmul__') :
    345             return N.dot(self, other)

ValueError: shapes (5,5) and (6,1) not aligned: 5 (dim 1) != 6 (dim 0)

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 transform matrix objects are:


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


Out[175]:
matrix([[ 0.+1.j,  0.+2.j],
        [ 0.+3.j,  0.+4.j]])

In [176]:
np.conjugate(C)


Out[176]:
matrix([[ 0.-1.j,  0.-2.j],
        [ 0.-3.j,  0.-4.j]])

Hermitian conjugate: transpose + conjugate


In [177]:
C.H


Out[177]:
matrix([[ 0.-1.j,  0.-3.j],
        [ 0.-2.j,  0.-4.j]])

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


In [179]:
np.real(C) # same as: C.real


Out[179]:
matrix([[ 0.,  0.],
        [ 0.,  0.]])

In [180]:
np.imag(C) # same as: C.imag


Out[180]:
matrix([[ 1.,  2.],
        [ 3.,  4.]])

Or the complex argument and absolute value


In [181]:
np.angle(C+1)


Out[181]:
array([[ 0.78539816,  1.10714872],
       [ 1.24904577,  1.32581766]])

In [182]:
np.abs(C)


Out[182]:
matrix([[ 1.,  2.],
        [ 3.,  4.]])

Matrix computations

Let's explore the linear algebra (linalg) methods:

Inverse


In [183]:
np.linalg.inv(C) # equivalent to C.I


Out[183]:
matrix([[ 0.+2.j ,  0.-1.j ],
        [ 0.-1.5j,  0.+0.5j]])

In [184]:
C.I * C


Out[184]:
matrix([[  1.00000000e+00+0.j,   0.00000000e+00+0.j],
        [  1.11022302e-16+0.j,   1.00000000e+00+0.j]])

Determinant


In [185]:
np.linalg.det(C)


Out[185]:
(2.0000000000000004+0j)

In [111]:
np.linalg.det(C.I)


Out[111]:
(0.50000000000000011+0j)

Data processing

Often it is useful to store datasets in Numpy arrays. Numpy provides a number of functions to calculate statistics of datasets in arrays.

For example, let's calculate some properties from the dataset defined before.


In [190]:
np.shape(data)


Out[190]:
(10, 7)

mean


In [192]:
np.mean(data[:,3])


Out[192]:
-11.83

standard deviations and variance


In [193]:
np.std(data[:,3]), np.var(data[:,3])


Out[193]:
(4.3011742582694783, 18.5001)

min and max


In [84]:
data[:,3].min()


Out[84]:
-19.300000000000001

In [194]:
data[:,3].max()


Out[194]:
-6.0999999999999996

sum, prod, and trace


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


Out[195]:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

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


Out[196]:
45

In [197]:
# product of all elements
np.prod(d+1)


Out[197]:
3628800

In [198]:
# cummulative sum
np.cumsum(d)


Out[198]:
array([ 0,  1,  3,  6, 10, 15, 21, 28, 36, 45])

In [199]:
# cummulative product
np.cumprod(d+1)


Out[199]:
array([      1,       2,       6,      24,     120,     720,    5040,
         40320,  362880, 3628800])

In [200]:
# same as: diag(A).sum()
np.trace(A)


Out[200]:
110

If an array as NaN elements, it is possible to use the same operations with the nan in their name: for instance, nanmax, nansum, etc. These operations mask all the NaN's in the data.


In [204]:
a = np.array([0,2,33.3,np.NaN,2.])
print np.max(a)
print np.nanmax(a)


nan
33.3

Another important feature, is finding the index of the maximum of an array. This is done with the function argmax (or nanargmax if the array contains NaN's).


In [80]:
print np.argmax(d)


9

Computations on subsets of arrays

We can compute with subsets of the data in an array using indexing, fancy indexing, and the other methods of extracting data from an array (described above).

For example, let's consider a temperature dataset:


In [222]:
!head -n 3 stockholm_td_adj.dat


1800  1  1    -6.1    -6.1    -6.1 1
1800  1  2   -15.4   -15.4   -15.4 1
1800  1  3   -15.0   -15.0   -15.0 1

The dataformat is: year, month, day, daily average temperature, low, high, location.

If we are interested in the average temperature only in a particular month, say February, then we can create a index mask and use it to select only the data for that month using:


In [297]:
data = np.loadtxt('stockholm_td_adj.dat.bz2')
np.unique(data[:,1]) # the month column takes values from 1 to 12


Out[297]:
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,  11.,
        12.])

In [224]:
mask_feb = data[:,1] == 2

In [225]:
# the temperature data is in column 3
np.mean(data[mask_feb,3])


Out[225]:
-3.2121095707365961

With these tools we have very powerful data processing capabilities at our disposal. For example, to extract the average monthly average temperatures for each month of the year only takes a few lines of code:


In [226]:
months = np.arange(1,13)
monthly_mean = [np.mean(data[data[:,1] == month, 3]) for month in months]


import matplotlib.pyplot as plt
%matplotlib inline
fig, ax = plt.subplots()
ax.bar(months, monthly_mean)
ax.set_xlabel("Month")
ax.set_ylabel("Monthly avg. temp.");


Calculations with higher-dimensional data

When functions such as min, max, etc. are 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 [227]:
m = random.rand(3,3)
m


Out[227]:
array([[ 0.90258753,  0.44483294,  0.59624183],
       [ 0.26680406,  0.87446277,  0.61826539],
       [ 0.47307416,  0.79684284,  0.5340052 ]])

In [228]:
# global max
m.max()


Out[228]:
0.90258752648090268

In [229]:
# max in each column
m.max(axis=0)


Out[229]:
array([ 0.90258753,  0.87446277,  0.61826539])

In [230]:
# max in each row
m.max(axis=1)


Out[230]:
array([ 0.90258753,  0.87446277,  0.79684284])

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 [231]:
A


Out[231]:
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 [232]:
n, m = A.shape

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


Out[233]:
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 [234]:
B[0,0:5] = 5 # modify the array

B


Out[234]:
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 [235]:
A # and the original variable is also changed. B is only a different view of the same data


Out[235]:
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 [236]:
B = A.flatten()

B


Out[236]:
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 [237]:
B[0:5] = 10

B


Out[237]:
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 [238]:
A # now A has not changed, because B's data is a copy of A's, not refering to the same data


Out[238]:
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]])

Now, a few more examples with some graphics.


In [290]:
array1 = np.arange(90).reshape((-1, 10))

In this case, one of the axis length is left as -1. Numpy will compute this dimension for you.


In [291]:
array1.shape


Out[291]:
(9, 10)

The array has 10 columns and 9 rows.

We can select one element with two indices:


In [292]:
array1[5,7]


Out[292]:
57

Or we can select an entire row:


In [293]:
array1[5,:]


Out[293]:
array([50, 51, 52, 53, 54, 55, 56, 57, 58, 59])

Part of a row:


In [294]:
array1[5,1:8]


Out[294]:
array([51, 52, 53, 54, 55, 56, 57])

Or a rectangle:


In [295]:
array1[5:-1,1:8]


Out[295]:
array([[51, 52, 53, 54, 55, 56, 57],
       [61, 62, 63, 64, 65, 66, 67],
       [71, 72, 73, 74, 75, 76, 77]])

We can even use non-sequential indexing:


In [296]:
array1[(5, 7), (6, 8)]


Out[296]:
array([56, 78])

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 [240]:
v = np.array([1,2,3])

In [241]:
v.shape


Out[241]:
(3,)

In [243]:
# make a column matrix of the vector v
v[:, np.newaxis]


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

In [244]:
# column matrix
v[:,np.newaxis].shape


Out[244]:
(3, 1)

In [245]:
# row matrix
v[np.newaxis,:].shape


Out[245]:
(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 [246]:
a = np.array([[1, 2], [3, 4]])

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


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

In [248]:
# tile the matrix 3 times 
np.tile(a, 3)


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

concatenate


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

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


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

In [251]:
np.concatenate((a, b.T), axis=1)


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

hstack and vstack


In [252]:
np.vstack((a,b))


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

In [253]:
np.hstack((a,b.T))


Out[253]:
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 (technical term: pass by reference).


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

A


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

In [255]:
# now B is referring to the same array data as A 
B = A

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

B


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

In [257]:
A


Out[257]:
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 [261]:
B = A.copy()

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

B


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

In [263]:
A


Out[263]:
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 [264]:
v = np.array([1,2,3,4])

for element in v:
    print(element)


1
2
3
4

In [265]:
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 [270]:
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 [271]:
# each element in M is now squared
M


Out[271]:
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 [273]:
def Theta(x):
    """
    Scalar implemenation of the Heaviside step function.
    """
    if x >= 0:
        return 1
    else:
        return 0

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


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

<ipython-input-273-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 a 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 [275]:
Theta_vec = np.vectorize(Theta)

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


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

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


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

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


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

In [279]:
# still works for scalars as well
Theta(-1.2), Theta(2.6)


Out[279]:
(0, 1)

Another example:


In [288]:
def funct3(val):
    if val > 3: # Doesn’t work with array
        x = 2
    else:
        x = 5
    return x

This function does not work with arrays.

So, we have to redefine it with vectorize:


In [289]:
vfunct3 = np.vectorize(funct3)
vfunct3(np.array([3,4,5,1,2])) # Now works!


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

Using arrays in conditions

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


In [280]:
M


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

In [281]:
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 [282]:
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 [283]:
M.dtype


Out[283]:
dtype('int64')

In [284]:
M2 = M.astype(float)

M2


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

In [285]:
M2.dtype


Out[285]:
dtype('float64')

In [286]:
M3 = M.astype(bool)

M3


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

Further reading

Versions


In [298]:
%reload_ext version_information

%version_information numpy


Out[298]:
SoftwareVersion
Python2.7.12 64bit [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
IPython5.1.0
OSLinux 4.4.0 47 generic x86_64 with debian jessie sid
numpy1.11.2
Tue Dec 20 17:36:46 2016 PST

In [ ]: