import numpy as np
14 Numpy
We will follow here this excellent chapter from Wes MacKinney’s book.
In particular the subtitles:
- Creating ndarray
- Arithmetic with numpy arrays
- Basic indexing and slicing
- Boolean indexing
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:
= np.arange(12).reshape(3,4)
arr arr
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
# Take first row
0] arr[
array([0, 1, 2, 3])
# Take first column
0] arr[:,
array([0, 4, 8])
# Take every second element of second row
1, ::2] arr[
array([4, 6])
# Take every second element of third column
2, 2] arr[::
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
1, 2]] arr[:, [
array([[ 1, 2],
[ 5, 6],
[ 9, 10]])
# Take first and third rows
0, 2], :] arr[[
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
= np.arange(25)
arr 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])
5,5) arr.reshape(
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]])
- Reshape
arr
to be a square matrix, call itarr_sq
. - Extract the values at this coordinates [(0, 3), (2, 4), (3, 2)].
- Extract one index operation the elements 1, 4, 9, 11, 21.
- Create a boolean mask that will extract the odd numbers from the
arr_sq
. - Find the indices of the even elements off
arr_sq
. - Flatten
arr_sq
into 1 dimension. - Get the third column of
arr_sq
. - Get the second and the fourth rows of
arr_sq
. - Compute the dot product between
arr_sq
andarr_sq
transposed. - Extract the upper right triangle values (including the diagonal.
- Create a square matrix of 25 elements filled only with the value 100 along the main diagonal
- Create a square matrix of 25 elements filled only with the value 1 the counter-diagonal.