A Short Tutorial on NumPy


In [1]:
import numpy as np
In [2]:
print(np.__version__)
1.23.1

Creating vectors as matrices using NumPy arrays¶

In [3]:
# Creating a vector

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

print('v =', v)
v = [1 2 3 4 5]
In [4]:
# Creating a matrix

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

print('A =\n', A)
A =
 [[1 2 3]
 [4 5 6]
 [7 8 9]]

Adding a scalar to a matrix¶

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

print('A =\n', A)

A = A + 10

print('\nA + 10 =\n', A)
A =
 [[1 2 3]
 [4 5 6]
 [7 8 9]]

A + 10 =
 [[11 12 13]
 [14 15 16]
 [17 18 19]]
In [6]:
# Similarly, subtracting:

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

print('A =\n', A)

A = A - 10

print('\nA - 10 =\n', A)
A =
 [[1 2 3]
 [4 5 6]
 [7 8 9]]

A - 10 =
 [[-9 -8 -7]
 [-6 -5 -4]
 [-3 -2 -1]]

Adding a NumPy array (as a row vector) to a matrix¶

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

print('A =\n', A)

v = np.array([10,11,12])

A = A + v

print('\nA + v =\n', A)
A =
 [[1 2 3]
 [4 5 6]
 [7 8 9]]

A + v =
 [[11 13 15]
 [14 16 18]
 [17 19 21]]

NumPy arrays are treated as row vectors. Errors will occur if the dimensions do not match.¶

In [8]:
A = np.array([[1, 2], [3, 4] , [5, 6], [7, 8]])

print('A =\n', A)

v = np.array([10,11])

A = A + v # ok

print('\nA + v =\n', A)

v2 = np.array([10,11,12,13]) # Error

A = A + v2

print('\nA + v2 =\n', A)
A =
 [[1 2]
 [3 4]
 [5 6]
 [7 8]]

A + v =
 [[11 13]
 [13 15]
 [15 17]
 [17 19]]
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [8], in <cell line: 13>()
      9 print('\nA + v =\n', A)
     11 v2 = np.array([10,11,12,13]) # Error
---> 13 A = A + v2
     15 print('\nA + v2 =\n', A)

ValueError: operands could not be broadcast together with shapes (4,2) (4,) 

Matrix multiplication¶

In [9]:
A1 = np.array([[1,2], [3,4], [5,6]])

print('A1 =\n', A1)

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

print('\nA2 =\n', A2)

A3 = A1 @ A2 # Matrix multiplication

print('\nA1 @ A2 =\n', A3)

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

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

A4 = A1 * A2 # Matrix Hadamard Product

print('\nA1 * A2 =\n', A4)
A1 =
 [[1 2]
 [3 4]
 [5 6]]

A2 =
 [[1 2]
 [3 4]]

A1 @ A2 =
 [[ 7 10]
 [15 22]
 [23 34]]

A1 * A2 =
 [[ 1  4]
 [ 9 16]
 [25 36]]

Operations on Matrices¶

In [10]:
A1 = np.array([[1,2], [3,4], [5,6]])

print('A1 =\n', A1)

print('\nA1.sum() :', A1.sum()) # sum of matrix elements

print('\nA1.sum(axis=0) :', A1.sum(axis=0)) # sum of matrix columns

print('\nA1.sum(axis=1) :', A1.sum(axis=1)) # sum of matrix rows

print('\nA1.mean() :', A1.mean()) # mean of matrix elements

print('\nA1.mean(axis=0) :', A1.mean(axis=0)) # mean of matrix columns

print('\nA1.var() :', A1.var()) # variance of matrix elements

print('\nA1.max() :', A1.max()) # maximum of matrix elements

print('\nA1.min() :', A1.min()) # minimum of matrix elements
A1 =
 [[1 2]
 [3 4]
 [5 6]]

A1.sum() : 21

A1.sum(axis=0) : [ 9 12]

A1.sum(axis=1) : [ 3  7 11]

A1.mean() : 3.5

A1.mean(axis=0) : [3. 4.]

A1.var() : 2.9166666666666665

A1.max() : 6

A1.min() : 1

Obtaining specific rows or columns¶

In [11]:
A1 = np.array([[1,2], [3,4], [5,6]])

print('A1 =\n', A1)

print('\nA1[:,0] =', A1[:,0]) # first column

print('\nA1[1,:] =', A1[1,:]) # second row
A1 =
 [[1 2]
 [3 4]
 [5 6]]

A1[:,0] = [1 3 5]

A1[1,:] = [3 4]

Reshaping arrays¶

In [12]:
A1 = np.array([[1,2], [3,4], [5,6]])

print('A1 =\n', A1)

print('\nA1.reshape(2,3) :\n', A1.reshape(2,3))

print('\nA1.reshape(6) :\n', A1.reshape(6))
A1 =
 [[1 2]
 [3 4]
 [5 6]]

A1.reshape(2,3) :
 [[1 2 3]
 [4 5 6]]

A1.reshape(6) :
 [1 2 3 4 5 6]

Different ways of creating specific arrays¶

In [13]:
Z = np.zeros((2,3)) # zeroes-filled array

print('Z = \n', Z)

O = np.ones((4,2)) # ones-filled array

print('\nO = \n', O) 

I = np.eye(3) # identity matrix

print('\nI = \n', I) 

R = np.random.rand(3,2) # matrix filled with uniformly random values in [0,1]

print('\nR = \n', R)

A = np.arange(10) # integers from 0 to n-1

print('\nA = \n', A)
Z = 
 [[0. 0. 0.]
 [0. 0. 0.]]

O = 
 [[1. 1.]
 [1. 1.]
 [1. 1.]
 [1. 1.]]

I = 
 [[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

R = 
 [[0.48416501 0.6138821 ]
 [0.88550324 0.40002371]
 [0.52653448 0.835859  ]]

A = 
 [0 1 2 3 4 5 6 7 8 9]




Some examples of using Matplotlib


In [14]:
import matplotlib

print(matplotlib.__version__)
3.5.2
In [15]:
import matplotlib.pyplot as plt

A simple plot¶

In [16]:
x = np.array([1,2,3,4,5])

y = np.array([10,5,15,7,12])

plt.plot(x, y)

plt.show()

A simple scatter plot¶

In [17]:
x = np.array([1,2,3,4,5])

y = np.array([10,5,15,7,12])

plt.figure(dpi=120)

plt.plot(x, y)

plt.show()