Numpy examples

import numpy as np

some handy functions

  • arange

  • linspace

a = np.arange(start=0, stop=10) 
print(a)## Note start value included, stop value excluded
b = np.arange(10) 
print(b)
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
a = np.linspace(start=0, stop=10, num=10, endpoint=True)
print(a) # Note: Note start value included, stop value included, num=10 evenly spaced numbers 

b = np.linspace(start=0, stop=10, num=10, endpoint=False)
print(b) # Note: Note start value included, stop value excluded, num=10 evenly spaced numbers 
[ 0.          1.11111111  2.22222222  3.33333333  4.44444444  5.55555556
  6.66666667  7.77777778  8.88888889 10.        ]
[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
a, step = np.linspace(start=0, stop=10, num=10, endpoint=True, retstep=True)

print(step) # step when endpoint included

b, step = np.linspace(start=0, stop=10, num=10, endpoint=False, retstep=True)

print(step) # step when endpoint excluded
1.1111111111111112
1.0

vectors

vector = np.array([1,2,3,4,5])
vector_row = np.array([[1, 2, 3, 4, 5]])
vector_column = np.array([[1],[2],[3],[4], [5]])


print(vector.shape)
print(vector_row.shape)
print(vector_column.shape)
(5,)
(1, 5)
(5, 1)
print(vector.reshape(5,1).shape)
print(vector.reshape(-1,1).shape)
print(vector_row.T.shape)
(5, 1)
(5, 1)
(5, 1)

matrices

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

print(A.shape)
print(A.T.shape)
print(A.reshape(2,3).shape)
print('*'*20)
print(A)
print('*'*20)
print(A.T)
print('*'*20)
print(A.reshape(2,3))
(3, 2)
(2, 3)
(2, 3)
********************
[[1 2]
 [3 4]
 [5 6]]
********************
[[1 3 5]
 [2 4 6]]
********************
[[1 2 3]
 [4 5 6]]

some special matrices

identity = np.eye(3)
zeros = np.zeros((3,3))
diagonal = np.diag(np.array([1,2,3]))

print(identity)
print('*'*20)
print(zeros)
print('*'*20)
print(diagonal)
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
********************
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]
********************
[[1 0 0]
 [0 2 0]
 [0 0 3]]

data types

A = np.diag(np.array([1,1,1]))
B = np.eye(3)

print(A)
print('*'*20)
print(B)

print("Are A and B the same?")
print('*'*20)
print(f'the data in A is {A.dtype}')
print(f'the data in B is {B.dtype}')
[[1 0 0]
 [0 1 0]
 [0 0 1]]
********************
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
Are A and B the same?
********************
the data in A is int32
the data in B is float64
## to specify the data type 

A = np.diag(np.array([1,1,1], dtype='float64'))
print(A)
print('*'*20)
# alternatively

A = np.diag(np.array([1.,1,1]))
print(A)

print('*'*20)
np.array(1).dtype, np.array(1.).dtype
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
********************
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
********************
(dtype('int32'), dtype('float64'))