Skip to main content

Numerical operations using numpy

Creating numpy array:

import numpy as np
my_array = np.array([1, 3, 4])
print(my_array)
type(my_array)

Create a two-dimensional array/matrix:

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

Check dimension of an array:

my_array2.ndim
my_array2.shape
my_array2.size
my_array2.dtype

We can specify the dtype explicitly if you need to.

my_array3 = np.array([[1, 4, 7], [1, 9, 32]], dtype=np.float64)
my_array3.dtype

We can switch type of an existing array:

my_array3.astype(np.int64)

Alternative way:

my_array3 = np.array(my_array3, dtype=np.float64)
print(my_array3)

Creating zero matrices:

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

Matrix of ones:

my_ones_array = np.ones((2, 3))
print(my_ones_array)

If we need to fill the matrix with some other constant, we can first create ones_matrix and multiply. However there is another function to do the same.

my_const_array = np.full([2, 3], 5)
print(my_const_array)

Create arrays with incremental sequences:

my_array4 = np.arange(1, 10, 2)
print(my_array4)
my_array5 = np.linspace(1, 10, 10)
print(my_array5)

Create meshgrid:

x = np.array([-1, 0, 1])
y = np.array([-2, 0, 2])

X, Y = np.meshgrid(x, y)
print(X, '\n\n', Y)

Other useful matrices:

np.identity(4)
np.eye(4)
np.eye(4, k=1)
np.eye(4, k=-1)
np.diag(np.arange(0, 20, 5))

Create random matrix:

np.random.rand(3)
np.random.rand(2, 3)

Normally distributed random numbers:

my_array_10 = np.random.randn(5); my_array_10

Expand matrix with numpy.tile():

my_array_11 = np.array([[1, 3], [2, 5]]); my_array_11
my_array_12 = np.tile(my_array_11, 2); my_array_12
my_array_12 = np.tile(my_array_11, (3, 2)); my_array_12

Indexing and slicing matrix:

my_array = np.arange(5); my_array
print(my_array[0], my_array[-1])

Reversing an array:

my_array[::-1]

Indexing in higher dimensional array:

my_array = np.array([[1, 3, 2], [1, 4, 2], [5, 3, 1]]); print(my_array)
my_array[2, 1]
my_array[2, :]

Masking/substituting array values based on criteria:

import numpy as np

a = np.random.rand(10)
print(a)

# sample output
[0.80182435 0.94238444 0.42435805 0.03047743 0.20772764 0.63607548
0.17445815 0.32827581 0.5017025 0.33546651]

b = np.array(a) # make a deep copy
b[a>0.5] = 1
b[a<=0.5] = 0

print(b)

# output
[1. 1. 0. 0. 0. 1. 0. 0. 1. 0.]