Knowing numpy Through The Really Tough Questions
By: Soumyajit Pal
Tags: Python Programming, Random Number Generator, Arrays, Numpy, Data Science

Photo by Emily Morter on Unsplash

Arguably the most versatile Python library, numpy is efficient, fast and interoperable. In this post, we walk through use-cases demonstrating the power of numpy.

1. Import the numpy package under the name np

as keyword renames numpy to np

2. Print the numpy version and the configuration

Everyone may not be using the same version of numpy

3. Create a null vector of size 10

zeros( ) from numpy creates null vector (contains only 0s)

4. Find memory size of an array

arange( ) generates elements from 1 to 6 (not including) in intervals of 1 (specified by 3rd argument)

5. Get the documentation of numpy add function

pass the name of function (in this case, add) to info( ) method of numpy

6. Create a null vector of size 10 with fifth value as 1

Passing concatenated lists to array( ) method of numpy, where * is used to repeat elements

7. Create a vector with values ranging from 10 to 49

arange( ) of numpy creates an array from 10 to 50 (excluding) with step size of 1

8. Reverse a vector

Using slicing and negative indexing

9. Create a 3 x 3 matrix with values ranging from 0 to 8

reshape( ) re-arranges the vector from arange( ) into 3 x 3 matrix

10. Find indices of non-zero elements from [1, 2, 0, 0, 4, 0]

nonzero( ) method of numpy returns list of indices of non-zero elements in a numpy array

11. Create a 3 x 3 identity matrix

eye(m) method creates an m x m identity matrix

12. Create a 3 x 3 x 3 array with random values

random_array is a 3 x 3 x 3 matrix with 27 random integers form 1 to 100 (exclusive)

13. Create a 10 x 10 array with random values and find the minimum and maximum values

min( ) and max( ) from numpy find minimum and maximum values respectively from a numpy array:

Finding minimum and maximum values from a matrix of random integers ranging from -100 to 100 (exclusive)

14. Create a random vector of size 30 and find the mean value

mean( ) from numpy finds the average of all values in a numpy array:

rand_vec_mean is a numpy vector with 30 random integers from -30 to 30 (exclusive)

15. Create a 2-D array with 1 on the border and 0 inside

Starting with a matrix of only ones, we fill all rows and columns from index 1 and go up to but including the last index:

the_array is a 5 x 5 matrix with required values

16. How to add a border (filled with 0s) around an existing array?

Around a matrix of random integers, we add a padding of 0s using the pad( ) method of numpy. The resultant matrix is re-assigned to the original array:

We want a constant (mode, constant_values) width of 0s of two rows and two columns (pad_width)

17. Find the result of the following expressions

0 * np.nan

Any mathematical computation on nan value returns nan itself

np.nan == np.nan

nan values are undefined and compare to False

np.inf > np.nan

Since nan is undefined, it is unclear whether it is lesser than infinity (np.inf)

np.nan - np.nan

Subtracting nan from nan yields nan!

0.3 == 3 * 0.1

Float is not stored as it is, but with greater precision. Therefore, 3 * 0.1 will not result in exactly 0.3

18. Create a 5 x 5 matrix with values 1, 2, 3, 4 just below the diagonal

The diag( ) function in numpy creates a matrix based on size of the diagonal. With 4 values just below the diagonal, the diagonal itself consists of exactly 5 elements. The parameter k (default value is 0) is set to -1 which denotes elements just below the diagonal and these elements are generated using arange( ) method:

diag( ) method creates a 5 x 5 matrix with elements below the diagonal generated from arange( )

19. Create 8 x 8 matrix and fill it with checkerboard pattern

Checkerboard pattern refers to alternating zeros and ones across rows and columns. We create a matrix of zeros and start filling in ones at required positions:

We want integer values only, thus the dtype parameter is set to int

Let’s fill every alternate row with alternate 1s:

Alternate rows with alternate 1s

Let’s fill alternate column with alternate 1s (opposite of above step):

Checkerboard matrix!

20. Consider a (6, 7, 8) shape array, find the index (x, y, z) of 100th element

The unravel_index( ) function of numpy finds the positional value of arbitrary elements of matrices represented in either row-major order or column-major order:

order = “C” considers matrix of given shape (denoted by tuple) stored in row-major order

order = “F” considers matrix of given shape (denoted by tuple) stored in column-major order

21. Create a checkerboard 8 x 8 matrix using the tile function

We start with a 2 x 2 matrix of alternating 0s and 1s:

Need to extend this using tile( )

The tile( ) method of numpy takes the above matrix and replicates it across rows and columns four at a time(denoted by the tuple argument):

Checkerboard matrix of 0s and 1s

22. Normalize a 5 x 5 random matrix

Normalization of a number is the ratio of two terms. The numerator is obtained by subtracting the minimum value of the entire set from the number which we are normalizing. The denominator is obtained by subtracting the minimum value of the entire set from the maximum value of the entire set:

random_matrix is 5 x 5 matrix of random integers between -20 to 20 (exclusive)

Computing minimum and maximum values using np.min( ) and np.max( ) respectively:

Finding minimum and maximum values of random_matrix

After normalization, all values lie within 0 and 1:

random_matrix has been normalized

23. Multiply a 5 x 3 matrix by a 3 x 2 matrix (real matrix product)

Matrix multiplication is possible because no. of columns in first matrix = no. of rows in second matrix

24. Given a 1D array, negate elements which are between 3 and 8, in place

We start by framing a conditional statement which will filter out elements between 3 and 8. This is followed by indexing the random vector on the condition. Elements which satisfy the given range, are multiplied by -1 to yield negations:

Generating random numbers between 1 and 10 (exclusive) and negating those that lie between 3 and 8

25. How can we find common values between two numpy arrays?

The intersect1d( ) function returns the intersection between two numpy arrays:

arr1 and arr2 are two numpy arrays of random integers; their common elements are stored in intersection

26. Create a vector of size 10 with values ranging from 0 to 1, both excluded

The linspace( ) function in numpy returns evenly spaced numbers over a specified interval starting with the lower range and ending at the upper range. Since we require 10 values exclusive of the starting and ending points, we pass 12 as the element count (denoted by parameter num) and exclude the limits using slicing:

Excluding 0 and 1, using [1 : -1], we store remaining 10 elements in x

27. Create a random vector of size 10 and sort it

Applying the built-in sort( ) method of numpy on an array created from 10 random integers in the range -10 to 20 (any other interval would also work) does the job:

sort( ) method returns the sorted sequence of random integers

28. Consider two random arrays A and B. Check if they are equal

Two arrays are said to be equal if and only if all corresponding elements match. The all( ) function along with the equality condition yields the desired results:

all( ) returns True only when all the corresponding elements in A and B are equal

29. Create a random vector of size 10 and replace the maximum value by -1

We start by creating a vector of floats between 0 and 1 (exclusive) using the random( ) function of numpy. The argmax( ) function returns the positional value of the maximum float. We index the vector at this position by inserting -1:

Displaying rand_vec before and after inserting -1

I hope you found this post helpful. Please feel free to leave your comments, feedback, criticism, thoughts and everything else that comes along with them. See you soon!