Top 5 Numpy Excersices for Beginners (Python Solutions)

Top 5 Numpy Excersices for Beginners

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 5 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

5 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]]

Weekly Contest 247

Biweekly Contest 55

June Long Challenge 2021 Solutions

March Long Challenge 2021 Solutions

April Long Challenge 2021 Solutions

Codechef Long Challenge Solutions

February Long Challenge 2021

January Long Challenge 2021

November Challenge 2020 SOLUTION CodeChef

October Lunchtime 2020 CodeChef SOLUTIONS

Related :

Related :

Leave a Comment