Python Matrix Creation

0
464
Creating Python Matrix

This post will cover various ways to create a python matrix.

We will need the following import the numpy libraries:

import numpy as np

A python matrix can only contain the same data types. If it contains different data types it will do a conversion so all elements have the same data type. For example if a list that is used to create a matrix contains a mixture integers and strings, it will convert all elements of a matrix into a string.

There are two ways using numpy to create matrix.

np.reshape()
np.array()

 

np.reshape()

Let’s discuss how to use the first method in creating a python matrix.

The 1st numpy function takes in as arguments the following:

np.reshape( data , (number of rows, number of columns) , order )

The 1st argument is the data to be converted into a matrix. In our case it will be a list but it can be another data type such as an numpy array.

The 2nd argument is the the shape of the matrix denoted by the (row,columns)

The 3rd argument is order which determines the how the elements of your data will be placed in the matrix. It can be either order= 'C'  (default) or order= 'F'.

The order='C' populates the matrix row by row. While the order='F' populates by columns.

For you to understand let’s create an example:

Let’s create a list with 9 elements:

mylist= [1,2,3,4,5,6,7,8,9]
# the code above have the same output as mylist= list(range(1,9))

Now let’s create a 3X3 python matrix using reshape:

Input:

np.reshape(mylist, (3,3))

Output:

array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

You can see here that we didn’t specify the order in the code. But as mentioned above if nothing is specified the default is order=’C’.

With order=’C’ the first row was populated first followed by the second row then lastly the third row.

Lets do another example but lets try creating a matrix with the order =’F’

Input:

np.reshape(mylist, (3,3), order='F')

Output:

array([[1, 4, 7],
       [2, 5, 8],
       [3, 6, 9]])

By using the order= ‘F’ we can see that the matrix was populated column by column.

np.array()

The second method to create a matrix is to call np.array() function.

It takes in various objects such as multiple lists and combines them into a matrix.

Let’s do an example by creating three lists.

listone = [1,2,3]
listtwo= [4,5,6]
listthree= [7,8,9]

Then let’s combine the three lists to create a matrix:

Input:

np.array([listone ,listtwo ,listthree])

Output:

array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

There you go we have created a 3X3 matrix.

Now you have learned how to create a matrix the next step is to learn how to index/slice a matrix. 

For official documentation visit the following:

numpy.reshape():

https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html

numpy.array()

https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here