How To Create Vectors And Matrices With Numpy

Next Story

Intro To Matrices With Python And Numpy

Numpy Vectors And Matrices

 

Numpy vectors and matrices will show up all the time in data science and machine learning.

So, let’s take a look at how to create them.

Let’s first import numpy.


import numpy as np

Next, let’s try to create our first vector row.


np.array([1,2,3,4])
# array([1, 2, 3, 4])

Wasn’t too bad was it?

Now, let’s try to make a single column vector.


np.array([[1],[2],[3],[4]])
# array([[1],[2],[3],[4]])

Now that we have created a row and a column, let’s combine these techniques to create a matrix.


np.array([[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]])
# array([[1, 2, 3, 4],[1, 2, 3, 4],[1, 2, 3, 4],[1, 2, 3, 4]])

It is pretty straight forward but it is definitely useful to know!

Full code example:


import numpy as np

np.array([1,2,3,4])
# array([1, 2, 3, 4])

np.array([[1],[2],[3],[4]])
# array([[1],[2],[3],[4]])

np.array([[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]])
# array([[1, 2, 3, 4],[1, 2, 3, 4],[1, 2, 3, 4],[1, 2, 3, 4]])

 

https://www.googletagmanager.com/gtag/js?id=UA-63695651-4