#!/usr/bin/env python # coding: utf-8 # # Numpy - multidimensional data arrays # J.R. Johansson (jrjohansson at gmail.com) # # The latest version of this [IPython notebook](http://ipython.org/notebook.html) lecture is available at [http://github.com/jrjohansson/scientific-python-lectures](http://github.com/jrjohansson/scientific-python-lectures). # # The other notebooks in this lecture series are indexed at [http://jrjohansson.github.io](http://jrjohansson.github.io). # In[1]: # what is this line all about?!? Answer in lecture 4 get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.pyplot as plt # ## 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[2]: from numpy import * # 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 = array([1,2,3,4]) v # In[4]: # a matrix: the argument to the array function is a nested Python list M = array([[1, 2], [3, 4]]) M # The `v` and `M` objects are both of the type `ndarray` that the `numpy` module provides. # In[5]: type(v), type(M) # 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 # In[7]: M.shape # The number of elements in the array is available through the `ndarray.size` property: # In[8]: M.size # Equivalently, we could use the function `numpy.shape` and `numpy.size` # In[9]: shape(M) # In[10]: size(M) # So far the `numpy.ndarray` looks awfully 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[11]: M.dtype # We get an error if we try to assign a value of the wrong type to an element in a numpy array: # In[12]: M[0,0] = "hello" # If we want, we can explicitly define the type of the array data when we create it, using the `dtype` keyword argument: # In[13]: M = array([[1, 2], [3, 4]], dtype=complex) M # 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 impractical 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[14]: # create a range x = arange(0, 10, 1) # arguments: start, stop, step x # In[15]: x = arange(-1, 1, 0.1) x # #### linspace and logspace # In[16]: # using linspace, both end points ARE included linspace(0, 10, 25) # In[17]: logspace(0, 10, 10, base=e) # #### mgrid # In[18]: x, y = mgrid[0:5, 0:5] # similar to meshgrid in MATLAB # In[19]: x # In[20]: y # #### random data # In[21]: from numpy import random # In[22]: # uniform random numbers in [0,1] random.rand(5,5) # In[23]: # standard normal distributed random numbers random.randn(5,5) # #### diag # In[24]: # a diagonal matrix diag([1,2,3]) # In[25]: # diagonal with offset from the main diagonal diag([1,2,3], k=1) # #### zeros and ones # In[26]: zeros((3,3)) # In[27]: ones((3,3)) # ## 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[28]: get_ipython().system('head stockholm_td_adj.dat') # In[29]: data = genfromtxt('stockholm_td_adj.dat') # In[30]: data.shape # In[31]: fig, ax = plt.subplots(figsize=(14,4)) ax.plot(data[:,0]+data[:,1]/12.0+data[:,2]/365, data[:,5]) ax.axis('tight') ax.set_title('tempeatures in Stockholm') ax.set_xlabel('year') ax.set_ylabel('temperature (C)'); # Using `numpy.savetxt` we can store a Numpy array to a file in CSV format: # In[32]: M = random.rand(3,3) M # In[33]: savetxt("random-matrix.csv", M) # In[34]: get_ipython().system('cat random-matrix.csv') # In[35]: savetxt("random-matrix.csv", M, fmt='%.5f') # fmt specifies the format get_ipython().system('cat random-matrix.csv') # ### Numpy's native file format # Useful when storing and reading back numpy array data. Use the functions `numpy.save` and `numpy.load`: # In[36]: save("random-matrix.npy", M) get_ipython().system('file random-matrix.npy') # In[37]: load("random-matrix.npy") # ## More properties of the numpy arrays # In[38]: M.itemsize # bytes per element # In[39]: M.nbytes # number of bytes # In[40]: M.ndim # number of dimensions # ## Manipulating arrays # ### Indexing # We can index elements in an array using square brackets and indices: # In[41]: # v is a vector, and has only one dimension, taking one index v[0] # In[42]: # M is a matrix, or a 2 dimensional array, taking two indices M[1,1] # If we omit an index of a multidimensional array it returns the whole row (or, in general, a N-1 dimensional array) # In[43]: M # In[44]: M[1] # The same thing can be achieved with using `:` instead of an index: # In[45]: M[1,:] # row 1 # In[46]: M[:,1] # column 1 # We can assign new values to elements in an array using indexing: # In[47]: M[0,0] = 1 # In[48]: M # In[49]: # also works for rows and columns M[1,:] = 0 M[:,2] = -1 # In[50]: M # ### Index slicing # Index slicing is the technical name for the syntax `M[lower:upper:step]` to extract part of an array: # In[51]: A = array([1,2,3,4,5]) A # In[52]: A[1:3] # Array slices are *mutable*: if they are assigned a new value the original array from which the slice was extracted is modified: # In[53]: A[1:3] = [-2,-3] A # We can omit any of the three parameters in `M[lower:upper:step]`: # In[54]: A[::] # lower, upper, step all take the default values # In[55]: A[::2] # step is 2, lower and upper defaults to the beginning and end of the array # In[56]: A[:3] # first three elements # In[57]: A[3:] # elements from index 3 # Negative indices counts from the end of the array (positive index from the beginning): # In[58]: A = array([1,2,3,4,5]) # In[59]: A[-1] # the last element in the array # In[60]: A[-3:] # the last three elements # Index slicing works exactly the same way for multidimensional arrays: # In[61]: A = array([[n+m*10 for n in range(5)] for m in range(5)]) A # In[62]: # a block from the original array A[1:4, 1:4] # In[63]: # strides A[::2, ::2] # ### Fancy indexing # Fancy indexing is the name for when an array or list is used in-place of an index: # In[64]: row_indices = [1, 2, 3] A[row_indices] # In[65]: col_indices = [1, 2, -1] # remember, index -1 means the last element A[row_indices, col_indices] # 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[66]: B = array([n for n in range(5)]) B # In[67]: row_mask = array([True, False, True, False, False]) B[row_mask] # In[68]: # same thing row_mask = array([1,0,1,0,0], dtype=bool) B[row_mask] # This feature is very useful to conditionally select elements from an array, using for example comparison operators: # In[69]: x = arange(0, 10, 0.5) x # In[70]: mask = (5 < x) * (x < 7.5) mask # In[71]: x[mask] # ## Functions for extracting data from arrays and creating arrays # ### where # The index mask can be converted to position index using the `where` function # In[72]: indices = where(mask) indices # In[73]: x[indices] # this indexing is equivalent to the fancy indexing x[mask] # ### diag # With the diag function we can also extract the diagonal and subdiagonals of an array: # In[74]: diag(A) # In[75]: diag(A, -1) # ### take # The `take` function is similar to fancy indexing described above: # In[76]: v2 = arange(-3,3) v2 # In[77]: row_indices = [1, 3, 5] v2[row_indices] # fancy indexing # In[78]: v2.take(row_indices) # But `take` also works on lists and other objects: # In[79]: take([-3, -2, -1, 0, 1, 2], row_indices) # ### choose # Constructs an array by picking elements from several arrays: # In[80]: which = [1, 0, 1, 0] choices = [[-2,-2,-2,-2], [5,5,5,5]] choose(which, choices) # ## 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[81]: v1 = arange(0, 5) # In[82]: v1 * 2 # In[83]: v1 + 2 # In[84]: A * 2, A + 2 # ### Element-wise array-array operations # When we add, subtract, multiply and divide arrays with each other, the default behaviour is **element-wise** operations: # In[85]: A * A # element-wise multiplication # In[86]: v1 * v1 # If we multiply arrays with compatible shapes, we get an element-wise multiplication of each row: # In[87]: A.shape, v1.shape # In[88]: A * v1 # ### Matrix algebra # What about matrix multiplication? 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[89]: dot(A, A) # In[90]: dot(A, v1) # In[91]: dot(v1, v1) # 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[92]: M = matrix(A) v = matrix(v1).T # make it a column vector # In[93]: v # In[94]: M * M # In[95]: M * v # In[96]: # inner product v.T * v # In[97]: # with matrix objects, standard matrix algebra applies v + M*v # If we try to add, subtract or multiply objects with incompatible shapes we get an error: # In[98]: v = matrix([1,2,3,4,5,6]).T # In[99]: shape(M), shape(v) # In[100]: M * v # 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[101]: C = matrix([[1j, 2j], [3j, 4j]]) C # In[102]: conjugate(C) # Hermitian conjugate: transpose + conjugate # In[103]: C.H # We can extract the real and imaginary parts of complex-valued arrays using `real` and `imag`: # In[104]: real(C) # same as: C.real # In[105]: imag(C) # same as: C.imag # Or the complex argument and absolute value # In[106]: angle(C+1) # heads up MATLAB Users, angle is used instead of arg # In[107]: abs(C) # ### Matrix computations # #### Inverse # In[108]: linalg.inv(C) # equivalent to C.I # In[109]: C.I * C # #### Determinant # In[110]: linalg.det(C) # In[111]: linalg.det(C.I) # ### 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 Stockholm temperature dataset used above. # In[112]: # reminder, the temperature dataset is stored in the data variable: shape(data) # #### mean # In[113]: # the temperature data is in column 3 mean(data[:,3]) # The daily mean temperature in Stockholm over the last 200 years has been about 6.2 C. # #### standard deviations and variance # In[114]: std(data[:,3]), var(data[:,3]) # #### min and max # In[115]: # lowest daily average temperature data[:,3].min() # In[116]: # highest daily average temperature data[:,3].max() # #### sum, prod, and trace # In[117]: d = arange(0, 10) d # In[118]: # sum up all elements sum(d) # In[119]: # product of all elements prod(d+1) # In[120]: # cumulative sum cumsum(d) # In[121]: # cumulative product cumprod(d+1) # In[122]: # same as: diag(A).sum() trace(A) # ### 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 go back to the temperature dataset: # In[123]: get_ipython().system('head -n 3 stockholm_td_adj.dat') # 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[124]: unique(data[:,1]) # the month column takes values from 1 to 12 # In[125]: mask_feb = data[:,1] == 2 # In[126]: # the temperature data is in column 3 mean(data[mask_feb,3]) # 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[127]: months = arange(1,13) monthly_mean = [mean(data[data[:,1] == month, 3]) for month in months] 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[128]: m = random.rand(3,3) m # In[129]: # global max m.max() # In[130]: # max in each column m.max(axis=0) # In[131]: # max in each row m.max(axis=1) # 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 underlying data, which makes it a fast operation even for large arrays. # In[132]: A # In[133]: n, m = A.shape # In[134]: B = A.reshape((1,n*m)) B # In[135]: B[0,0:5] = 5 # modify the array B # In[136]: A # and the original variable is also changed. B is only a different view of the same data # We can also use the function `flatten` to make a higher-dimensional array into a vector. But this function creates a copy of the data. # In[137]: B = A.flatten() B # In[138]: B[0:5] = 10 B # In[139]: A # now A has not changed, because B's data is a copy of A's, not referring to the same data # ## 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[140]: v = array([1,2,3]) # In[141]: shape(v) # In[142]: # make a column matrix of the vector v v[:, newaxis] # In[143]: # column matrix v[:,newaxis].shape # In[144]: # row matrix v[newaxis,:].shape # ## 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[145]: a = array([[1, 2], [3, 4]]) # In[146]: # repeat each element 3 times repeat(a, 3) # In[147]: # tile the matrix 3 times tile(a, 3) # ### concatenate # In[148]: b = array([[5, 6]]) # In[149]: concatenate((a, b), axis=0) # In[150]: concatenate((a, b.T), axis=1) # ### hstack and vstack # In[151]: vstack((a,b)) # In[152]: hstack((a,b.T)) # ## Copy and "deep copy" # To achieve high performance, assignments in Python usually do not copy the underlying 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[153]: A = array([[1, 2], [3, 4]]) A # In[154]: # now B is referring to the same array data as A B = A # In[155]: # changing B affects A B[0,0] = 10 B # In[156]: A # 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[157]: B = copy(A) # In[158]: # now, if we modify B, A is not affected B[0,0] = -5 B # In[159]: A # ## 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[160]: v = array([1,2,3,4]) for element in v: print(element) # In[161]: M = array([[1,2], [3,4]]) for row in M: print("row", row) for element in row: print(element) # 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[162]: 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 # In[163]: # each element in M is now squared M # ## 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[164]: def Theta(x): """ Scalar implementation of the Heaviside step function. """ if x >= 0: return 1 else: return 0 # In[165]: Theta(array([-3,-2,-1,0,1,2,3])) # 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[166]: Theta_vec = vectorize(Theta) # In[167]: Theta_vec(array([-3,-2,-1,0,1,2,3])) # We can also implement the function to accept a vector input from the beginning (requires more effort but might give better performance): # In[168]: def Theta(x): """ Vector-aware implementation of the Heaviside step function. """ return 1 * (x >= 0) # In[169]: Theta(array([-3,-2,-1,0,1,2,3])) # In[170]: # still works for scalars as well Theta(-1.2), Theta(2.6) # ## 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 evaluates to `True`: # In[171]: M # In[172]: 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") # In[173]: if (M > 5).all(): print("all elements in M are larger than 5") else: print("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 creates a new array of new type: # In[174]: M.dtype # In[175]: M2 = M.astype(float) M2 # In[176]: M2.dtype # In[177]: M3 = M.astype(bool) M3 # ## Further reading # * http://numpy.scipy.org # * http://scipy.org/Tentative_NumPy_Tutorial # * http://scipy.org/NumPy_for_Matlab_Users - A Numpy guide for MATLAB users. # ## Versions # In[178]: get_ipython().run_line_magic('reload_ext', 'version_information') get_ipython().run_line_magic('version_information', 'numpy')