Python- Numpy Starter

Code effortlessly.

Numpy stands for Numerical Python. It is the library most suited if one wishes to work with matrices, arrays, transformations etc. Its simplicity and highly efficient algorithms have made numpy a must learn library.

Let us conduct an experiment to see how numpy performs over pythons ‘for loop’ :

In the below experiment we are trying to add corresponding elements in two arrays, i.e. 1st element of one array to 1st element of second array and likewise. At the end we can compare the time taken to complete the task.

from datetime import datetime
a = [2,3,4]*100000000
b = [2,4,4]*100000000

start =
c = []
for ai,bi in zip(a,b):
#total time taken

Using numpy to solve the same problem statement.

from datetime import datetime
import numpy as np
a = [2,3,4]*100000000
b = [2,4,4]*100000000

start =
a = np.array(a)
b = np.array(b)
c = a+b
#total time taken

We can conclude that numpy outperforms ‘for loops’ with very high margin.


“At the core of the NumPy package, is the ndarray object. This encapsulates n-dimensional arrays of homogeneous data types, with many operations being performed in compiled code for performance.” — Numpy documentation.

import numpy as np

a = np.array([1, 2, 3])
print("Type of the object: {} and shape: {}".format(type(a),a.shape))
print("elements in array {} {} {}".format(a[0], a[1], a[2]))

'''Changing values of element in the array'''
a[0] = 5
print("altered array: {}".format(a))

'''2D array'''
b = np.array([[1,2,3],[4,5,6]])
print("shape of the 2d array: {} ".format(b.shape))
print("{}, {}, {}".format(b[0, 0], b[0, 1], b[1, 0]))

We can create different type of numpy arrays by calling simple numpy methods.

import numpy as np

# creating matrix from numpy methods
ones = np.ones((2,2))

zeros = np.zeros((2,3))

mat = np.full((2,1), 7)

r_mat = np.random.random((3,3)) #creating random matrix

I = np.eye(3) #identity matrix

Numpy Indexing:

import numpy as np

np_matrix = np.random.randint(low=1,high=100,size=(5,5))
# to get the first row
# to get the first two rows
# to get the first two rows and 2 columns

# to get first element

Algebra of arrays:

import numpy as np

x = np.random.randint(low=1,high=10,size=(2,2))
y = np.random.randint(low=1,high=10,size=(2,2))

print(x + y)
print(np.add(x, y))

print(x - y)
print(np.subtract(x, y))

print(x * y)
print(np.multiply(x, y))

print(x / y)
print(np.divide(x, y))


Broadcasting of arrays:

import numpy as np

x = np.random.randint(low=1,high=10,size=(3,5))
y = np.random.randint(low=1,high=10,size=(1,5))


The ‘x+y’ will work even if x has shape (3,5) and y has shape (1,5) due to broadcasting. Y will actually have a shape (3,5), where each row was a copy of y, and then the elementwise summation will be performed.

Stacking of arrays:

Stack functions are helpful when we want merge two n-dim arrays (vertically or horizontally).

import numpy as np

x = np.random.randint(low=1,high=10,size=(2,2))
y = np.random.randint(low=1,high=10,size=(2,2))
z = np.hstack((x,y))
v = np.vstack((x,y))

Vectorizing functions via numpy:

To speed up operations on elements of a matrix we can vectorize a python function and apply on the matrix.

“The vectorized function evaluates pyfunc over successive tuples of the input arrays like the python map function, except it uses the broadcasting rules of numpy.” — numpy documentation.

import numpy as np

def change_number(x):
return x**2 + 3

x = np.random.randint(low=1,high=10,size=(5,5))
z = np.vectorize(change_number)

I hope the above concepts will help you code more efficiently using numpy arrays.

That’s all.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store