import numpy as np13 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
13.1 Slicing Arrays
Slicing works as with, for example, range, with systax (start, [stop], [step]). We treat each dimension separately with ,.
Let’s see:
arr = np.arange(12).reshape(3,4)
arrarray([[ 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]])
13.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.
13.3 Exercises
arr = np.arange(25)
arrarray([ 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]])
- Reshape
arrto 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_sqinto 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_sqandarr_sqtransposed. - 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.