NumPy

Introduction

Introduction

Creating NumPy arrays

import numpy as np
a = np.array([0,1,2])
b = np.array([3,4,5])

Can do basic element-wise operations on these.

import numpy as np
a = np.array([0,1,2])
b = np.array([3,4,5])
sum = a+b
minux = a-b
element_wise_product = a*b
divided = a/d
dot_product_scalar = a@b

You don’t need to use the symbols.

import numpy as np
a = np.array([0,1,2])
b = np.array([3,4,5])
sum = np.add(a, b)
minus = np.subtract(a,b)
element_wise_product = np.multiply(a,b)
divided = np.divide(a, b)
dot_product_scalar = np.dot(a,b)

Can also define ones like this

np.eye(n)
np.ones(i, j, k, ...)
np.full(i, j, k, ...)
np.rand(i, j, k, ...)
np.zeroes(i, j, k, ..)

Multi-dimensional arrays

import numpy as np
A = np.array([[0,1],[2,3]])
transposed = A.T
determinant = np.linalg.det(A)
inverse = np.linalg.inv(A)
eigenvalues, eigenvectors = np.linalg.eig(A)

Note that it’s .shape, not .shape()

import numpy as np
A = np.array([[0,1],[2,3]])
A.shape

We can multiply two matrices together. Note that using * would be elementwise, and probably not what is wanted.

import numpy as np
A = np.array([[0,1],[2,3]])
B = np.array([[4,5],[6,7]])
A@B

dtypes

import numpy as np
A = np.array([[0,1],[2,3]], dtype = np.int32)

Solving linear matrix equations

a = np.array([[1, 2], [3, 5]])
b = np.array([1, 2])
x = np.linalg.solve(a, b)
array([-1.,  1.])