import numpy as np
Let us start with lists.
# Create 2 lists
lst1 = [2, 3, 5, 1, 8]
lst2 = [2.2, 4.5, 3, 6.7, 5]
# Convert them into numpy arrays
np_l1 = np.array(lst1)
np_l2 = np.array(lst2)
print(type(np_l1))
print(np_l2)
<class 'numpy.ndarray'> [2.2 4.5 3. 6.7 5. ]
# Elementwise operations
l1_squared_per_l2 = np_l1**2 / np_l2
print(l1_squared_per_l2)
[ 1.81818182 2. 8.33333333 0.14925373 12.8 ]
# Elemenwise boolean operation
l1_squared_per_l2 < 2
array([ True, False, False, True, False])
# Choose the elements
l1_squared_per_l2[l1_squared_per_l2 < 2]
array([1.81818182, 0.14925373])
# Construct an equaly spaced array
np.linspace(0, 10, 11)
array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 100)
s = np.sin(x)
plt.plot(x, s)
[<matplotlib.lines.Line2D at 0x7effb56e3d30>]
# Construct matrices
m1 = np.array([(1,2,3), (4,5,6)])
print(m1)
[[1 2 3] [4 5 6]]
m2 = np.arange(1, 7).reshape(2, 3)
print(m2)
[[1 2 3] [4 5 6]]
m1.dtype
dtype('int64')
m3 = np.arange(1, 6, .9).reshape(2, 3)
print(m3)
[[1. 1.9 2.8] [3.7 4.6 5.5]]
m3.dtype
dtype('float64')
print(m3.size)
print(m3.shape)
6 (2, 3)
m4 = np.arange(8).reshape(2, 2, 2)
print(m4)
[[[0 1] [2 3]] [[4 5] [6 7]]]
m4.shape
(2, 2, 2)
# Unit matrix
u = np.eye(2) # eye pronounced as I
print(u)
[[1. 0.] [0. 1.]]
# Zero matrix
z = np.zeros((2, 3))
print(z)
[[0. 0. 0.] [0. 0. 0.]]
# Matrix of ones
o = np.ones((2, 3))
print(o)
[[1. 1. 1.] [1. 1. 1.]]
a = np.array([[1, 2], [3, 4]])
b = np.array([[1, 0], [2, 1]])
print(a)
print(b)
[[1 2] [3 4]] [[1 0] [2 1]]
# Elemenwise product
c = a*b
print(c)
[[1 0] [6 4]]
# Matrix product
d1 = a@b
# or
d2 = a.dot(b)
print(d1)
print(d2)
[[ 5 2] [11 4]] [[ 5 2] [11 4]]
rng = np.random.default_rng(1) # random number generator
m = rng.random((2,3))
print(m)
[[0.51182162 0.9504637 0.14415961] [0.94864945 0.31183145 0.42332645]]
m.sum()
3.290252281866131
m.min()
0.14415961271963373
m.max()
0.9504636963259353
# Elementwise evaluation
np.sin(m)
array([[0.48976625, 0.81368514, 0.14366081], [0.81262917, 0.30680228, 0.41079554]])
np.exp(m)
array([[1.6683275 , 2.58690892, 1.15506846], [2.58221988, 1.36592445, 1.52703271]])