Tutorial on Python Library: Numpy


Bikash Santra

Indian Statistical Institute, Kolkata


1. Import library

2. Single-dimensional arrays, behave similar to row vectors

3. Matrices: Two-dimensional arrays

4. Compatible operations for matrices and vectors

5. Random matrices

6. Reshaping matrices

7. Combining (or stacking) matrices

Exercise: Create two arrays of size 3x5 initialized with random integers drawn from (-100,100) and then vertically & horizontally stack them.

8. Dimension and shape of numpy arrays

9. Special Matrices

Exercise: Use np.arrange() function to create an array of size 4x2 where the elements will start from 0 to 14 (with step size 2) in row major oder

10. Numpy array operations: max, argmax, min, argmin, sort, argsort

Exercise: Generate an 1D array A with 20 elements randomly initialized with the numbers in [0,15]. Create another 1D array B with 20 elements randomly initialized with the numbers in [0,1]. Sort A and apply the sorted indices of A on B.

11. Statistical operations: mean, var, std...

12. Boolean Element-Wise Operations

13. Boolean 'Mask'

Some important operations in numpy

Exercise: Define a random matrix of shape 7x8. Fetch the number of rows and columns programatically. Then manipulate each element of the matrix with the following formula: x = sqrt((x+5)/10), x refers to the element of the matrix.

Exercise: Create a random array A of size 5x4. Using np.tile() function, add a random vector of size 4 with first three rows of A and add another random vector of size 4 with last two rows of A.

References

a) Numpy documentation
b) Numpy user guide