14  Numpy

We will follow here this excellent chapter from Wes MacKinney’s book.

In particular the subtitles:

14.1 Slicing Arrays

Slicing works as with, for example, range, with systax (start, [stop], [step]). We treat each dimension separately with ,.

Let’s see:

import numpy as np
arr = np.arange(12).reshape(3,4)
arr
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
# Take first row
arr[0]
array([0, 1, 2, 3])
# Take first column
arr[:, 0]
array([0, 4, 8])
# Take every second element of second row
arr[1, ::2]
array([4, 6])
# Take every second element of third column
arr[::2, 2]
array([ 2, 10])

One special thing about numpy slices: We can use lists to index. Each element of the list is interpreted as an index to get:

# Take second and third columns
arr[:, [1, 2]]
array([[ 1,  2],
       [ 5,  6],
       [ 9, 10]])
# Take first and third rows
arr[[0, 2], :]
array([[ 0,  1,  2,  3],
       [ 8,  9, 10, 11]])

14.2 Numpy Built-in Functions

Numpy implements many useful functions often used when working with numerical/scientific data. For example the random submodule exposes several useful functions for stochastic modelling and statistical analysis.

14.3 Exercises

arr = np.arange(25)
arr
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23, 24])
arr.reshape(5,5)
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])
  1. Reshape arr to be a square matrix, call it arr_sq.
  2. Extract the values at this coordinates [(0, 3), (2, 4), (3, 2)].
  3. Extract one index operation the elements 1, 4, 9, 11, 21.
  4. Create a boolean mask that will extract the odd numbers from the arr_sq.
  5. Find the indices of the even elements off arr_sq.
  6. Flatten arr_sq into 1 dimension.
  7. Get the third column of arr_sq.
  8. Get the second and the fourth rows of arr_sq.
  9. Compute the dot product between arr_sq and arr_sq transposed.
  10. Extract the upper right triangle values (including the diagonal.
  11. Create a square matrix of 25 elements filled only with the value 100 along the main diagonal
  12. Create a square matrix of 25 elements filled only with the value 1 the counter-diagonal.