Intro To Matrices With Python And Numpy
Matrices With Numpy
Numpy is really good at working with matrix mathematics, and matrix math is everywhere in data science.
It will save you a lot of time if you get acquainted with the numpy library.
Okay, without further ado, let’s get started by importing numpy and creating a sample matrix to work with.
import numpy as np
example_matrix = np.array([
[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]
])
One of the first things that we might want to do is get more info on our matrix.
Let’s first take a look at its shape. This will tell us the number of rows by the number of columns.
example_matrix.shape
# (4, 4)
Next, let’s take a look at how many elements are in our matrix.
example_matrix.size
# 16
Then, what if we wanted to know how many dimensions our data was? We got a function for that too.
example_matrix.ndim
# 2
Next, let’s get some statistical information on our matrix. Common statistical properties of a matrix are: min, max, mean, variance, and standard deviation.
np.min(example_matrix)
# 1
np.max(example_matrix)
# 16
np.mean(example_matrix)
# 8.5
np.var(example_matrix)
# 21.25
np.std(example_matrix)
# 4.6097722286464435
Sweet! That was a quick introduction to using matrices with numpy.
I hope you learned something new 🙂
Checkout the complete code example below.
import numpy as np
example_matrix = np.array([
[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]
])
example_matrix.shape
# (4, 4)
example_matrix.size
# 16
example_matrix.ndim
# 2
np.min(example_matrix)
# 1
np.max(example_matrix)
# 16
np.mean(example_matrix)
# 8.5
np.var(example_matrix)
# 21.25
np.std(example_matrix)
# 4.6097722286464435