What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

20 NumPy Exercises for Beginners (Python Solutions)

  • May 12, 2021
  • 10 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Navoneel Chakrabarty
20 NumPy Exercises for Beginners (Python Solutions)


NumPy is a computational library that helps in speeding up Vector Algebra operations that involve Vectors (Distance between points, Cosine Similarity) and Matrices. Specifically, it helps in constructing powerful n-dimensional arrays that works smoothly with distributed and GPU systems. It is a very handy library and extensively used in the domains of Data Analytics and Machine Learning. Other than Python, it can also be used in tandem with languages like C and Fortran. Being an Open Source Library under a liberal BSD license, it is developed and maintained publicly on GitHub. 

Here are 20 Basic NumPy Exercises which every beginner must go through and acquainted with.

NumPy Installation in Python

In the command line (cmd) type the following command,

pip install numpy

 

20 NumPy Exercises for Beginners


Importing NumPy and printing version number

import numpy as np

print(np.__version__)

 

Corresponding Output

1.19.2

 

EXERCISE 1 - Element-wise addition of 2 numpy arrays

Given are 2 similar dimensional numpy arrays, how to get a numpy array output in which every element is an element-wise sum of the 2 numpy arrays?

Sample Solution

a = np.array([[1,2,3],
              [4,5,6]])

b = np.array([[10,11,12],
              [13,14,15]])

c = a + b

print(c)

Corresponding Output

[[11 13 15]
 [17 19 21]]

 

EXERCISE 2 - Multiplying a matrix (numpy array) by a scalar

Given a numpy array (matrix), how to get a numpy array output which is equal to the original matrix multiplied by a scalar?

Sample Solution

a = np.array([[1,2,3],
              [4,5,6]])

b = 2*a # multiplying the numpy array a(matrix) by 2

print(b)

 

Corresponding Output

[[ 2  4  6]
 [ 8 10 12]]

 

EXERCISE 3 - Identity Matrix

Create an identity matrix of dimension 4-by-4

Sample Solution

i = np.eye(4)
print(i)

 

Corresponding Output

[[1. 0. 0. 0.]
 [0. 1. 0. 0.]
 [0. 0. 1. 0.]
 [0. 0. 0. 1.]]

 

EXERCISE 4 - Array re-dimensioning

Convert a 1-D array to a 3-D array

Sample Solution

a = np.array([x for x in range(27)])
o = a.reshape((3,3,3))
print(o)

 

Corrresponding Output

[[[ 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 25 26]]]

 

EXERCISE 5 - Array datatype conversion

Convert all the elements of a numpy array from float to integer datatype

Sample Solution

a = np.array([[2.5, 3.8, 1.5],
              [4.7, 2.9, 1.56]])

o = a.astype('int')

print(o)

 

Corresponding Output

[[2 3 1]
 [4 2 1]]

 

EXERCISE 6 - Obtaining Boolean Array from Binary Array

Convert a binary numpy array (containing only 0s and 1s) to a boolean numpy array

Sample Solution

a = np.array([[1, 0, 0],
              [1, 1, 1],
              [0, 0, 0]])

o = a.astype('bool')

print(o)

 

Corresponding Output

[[ True False False]
 [ True  True  True]
 [False False False]]

 

EXERCISE 7 - Horizontal Stacking of Numpy Arrays

Stack 2 numpy arrays horizontally i.e., 2 arrays having the same 1st dimension (number of rows in 2D arrays)

Sample Solution

a1 = np.array([[1,2,3],
               [4,5,6]])

a2 = np.array([[7,8,9],
               [10,11,12]])

o = np.hstack((a1, a2))

print(o)

 

Corresponding Output

[[ 1  2  3  7  8  9]
 [ 4  5  6 10 11 12]]

 

EXERCISE 8 - Vertically Stacking of Numpy Arrays

Stack 2 numpy arrays vertically i.e., 2 arrays having the same last dimension (number of columns in 2D arrays)

Sample Solution 

a1 = np.array([[1,2],
               [3,4],
               [5,6]])

a2 = np.array([[7,8],
               [9,10],
               [10,11]])

o = np.vstack((a1, a2))

print(o)

 

Corresponding Output

[[ 1  2]
 [ 3  4]
 [ 5  6]
 [ 7  8]
 [ 9 10]
 [10 11]]

 

EXERCISE 9 - Custom Sequence Generation

Generate a sequence of numbers in the form of a numpy array from 0 to 100 with gaps of 2 numbers, for example: 0, 2, 4 ....

Sample Solution

list_of_numbers = [x for x in range(0, 101, 2)]

o = np.array(list_of_numbers)

print(o)

Alternative Solution

o = np.arange(0, 101, 2)

print(o)

 

Corresponding Output

[  0   2   4   6   8  10  12  14  16  18  20  22  24  26  28  30  32  34
  36  38  40  42  44  46  48  50  52  54  56  58  60  62  64  66  68  70
  72  74  76  78  80  82  84  86  88  90  92  94  96  98 100]

 

EXERCISE 10 - Getting the positions (indexes) where elements of 2 numpy arrays match

From 2 numpy arrays, extract the indexes in which the elements in the 2 arrays match

Sample Solution

a = np.array([1,2,3,4,5])

b = np.array([1,3,2,4,5])

print(np.where(a == b))

 

Corresponding Output

(array([0, 3, 4], dtype=int64),)

 

EXERCISE 11 - Generation of given count of equally spaced numbers within a specified range

Output a sequence of equally gapped 5 numbers in the range 0 to 100 (both inclusive)

Sample Solution

o = np.linspace(0, 100, 5)

print(o)

 

Corresponding Output

[  0.  25.  50.  75. 100.]

 

EXERCISE 12 - Matrix Generation with one particular value

Output a matrix (numpy array) of dimension 2-by-3 with each and every value equal to 5

Sample Solution

o = np.full((2, 3), 5)

print(o)

Alternate Solution

a = np.ones((2, 3))

o = 5*a

print(o)

 

Corresponding Output

[[5 5 5]
 [5 5 5]]

 

EXERCISE 13 - Array Generation by repeatition of a small array across each dimension

Output an array by repeating a smaller array of 2 dimensions, 10 times

Sample Solution

a = np.array([[1,2,3],
              [4,5,6]])

o = np.tile(a, 10)

print(o)

 

Corresponding Output

[[1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3]
 [4 5 6 4 5 6 4 5 6 4 5 6 4 5 6 4 5 6 4 5 6 4 5 6 4 5 6 4 5 6]]

 

EXERCISE 14 - Array Generation of random integers within a specified range

Output a 5-by-5 array of random integers between 0 (inclusive) and 10 (exclusive)

Sample Solution

np.random.seed(123) # setting the seed

o = np.random.randint(0, 10, size = (5,5))

print(o)

 

Corresponding Output

[[2 2 6 1 3]
 [9 6 1 0 1]
 [9 0 0 9 3]
 [4 0 0 4 1]
 [7 3 2 4 7]]

 

EXERCISE 15 - Array Generation of random numbers following normal distribution

Output a 3-by-3 array of random numbers following normal distribution

Sample Solution

np.random.seed(123) # setting the seed

o = np.random.normal(size = (3,3))

print(o)

 

Corresponding Output

[[-1.0856306   0.99734545  0.2829785 ]
 [-1.50629471 -0.57860025  1.65143654]
 [-2.42667924 -0.42891263  1.26593626]]

 

EXERCISE 16 - Matrix Multiplication

Given 2 numpy arrays as matrices, output the result of multiplying the 2 matrices (as a numpy array)

Sample Solution

a = np.array([[1,2,3],
              [4,5,6],
              [7,8,9]])

b = np.array([[2,3,4],
              [5,6,7],
              [8,9,10]])

o = a@b

print(o)

Alternate Solution

a = np.array([[1,2,3],
              [4,5,6],
              [7,8,9]])

b = np.array([[2,3,4],
              [5,6,7],
              [8,9,10]])

o = np.matmul(a, b)

print(o)

 

Corresponding Output

[[ 36  42  48]
 [ 81  96 111]
 [126 150 174]]

 

EXERCISE 17 - Matrix Transpose

Output the transpose of a matrix (as numpy array)

Sample Solution

a = np.array([[1,2,3],
              [4,5,6],
              [7,8,9]])

a_transpose = a.T

print(a_transpose)

 

Corresponding Output

[[1 4 7]
 [2 5 8]
 [3 6 9]]

 

EXERCISE 18 - Sine of an Angle (in radians)

Calculate the sine of an array of angles (in radians) using NumPy

Sample Solution

angles = np.array([3.14, 3.14/2, 6.28])

sine_of_angles = np.sin(angles)

print('Sine of the given array of angles = ', sine_of_angles)

 

Corresponding Output

Sine of the given array of angles =  [ 0.00159265  0.99999968 -0.0031853 ]

 

EXERCISE 19 - Cosine Similarity

Calculate the cosine similarity of 2 vectors (as numpy arrays)

Sample Solution

angles = np.array([3.14, 3.14/2, 6.28])

cosine_of_angles = np.cos(angles)

print('Cosine of the given array of angles = ', cosine_of_angles)

 

Corresponding Output

[-9.99998732e-01  7.96326711e-04  9.99994927e-01]

 

EXERCISE 20 - Generating the array element indexes such that the array elements appear in ascending order

Output the array element indexes such that the array elements appear in the ascending order

Sample Solution

array = np.array([10,1,5,2])

indexes = np.argsort(array)

print(indexes)

 

Corresponding Output

[1 3 2 0]


Conclusion

These are the very basics of NumPy that every beginner should get their hands dirty with, in order to get started with Data Analytics and Machine Learning. In case you are stuck somewhere in any of the numpy exercises or need further clarification on a concept of data science or Python, FavTutor is always here to provide you with help from expert tutors 24/7.  

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Navoneel Chakrabarty
I'm Navoneel Chakrabarty, a Data Scientist, Machine Learning & AI Enthusiast, and a Regular Python Coder. Apart from that, I am also a Natural Language Processing (NLP), Deep Learning, and Computer Vision Enthusiast.