Learn Python practically and Get Certified .
Popular examples, reference materials, learn python interactively, python introduction.
- Getting Started
- Keywords and Identifier
- Python Comments
- Python Variables
- Python Data Types
- Python Type Conversion
- Python I/O and Import
- Python Operators
- Python Namespace
Python Flow Control
- Python if...else
- Python for Loop
- Python while Loop
- Python break and continue
- Python Pass
- Python Function
- Function Argument
- Python Recursion
- Anonymous Function
- Global, Local and Nonlocal
- Python Global Keyword
- Python Modules
- Python Package
- Python Numbers
- Python List
- Python String
- Python Dictionary
- Python File Operation
- Python Directory
- Python Exception
- Exception Handling
- User-defined Exception
Python Object & Class
- Classes & Objects
- Python Inheritance
- Multiple Inheritance
- Operator Overloading
Python Advanced Topics
- Python Iterator
- Python Generator
- Python Closure
- Python Decorators
- Python Property
- Python RegEx
- Python Examples
Python Date and time
- Python datetime Module
- Python datetime.strftime()
- Python datetime.strptime()
- Current date & time
- Get current time
- Timestamp to datetime
- Python time Module
- Python time.sleep()
Python List Comprehension
- Python Shallow Copy and Deep Copy
Python Matrices and NumPy Arrays
A matrix is a two-dimensional data structure where numbers are arranged into rows and columns. For example:
This matrix is a 3x4 (pronounced "three by four") matrix because it has 3 rows and 4 columns.
- Python Matrix
Python doesn't have a built-in type for matrices. However, we can treat a list of a list as a matrix. For example:
We can treat this list of a list as a matrix having 2 rows and 3 columns.
Be sure to learn about Python lists before proceed this article.
Let's see how to work with a nested list.
When we run the program, the output will be:
Here are few more examples related to Python matrices using nested lists.
- Add two matrices
- Transpose a Matrix
- Multiply two matrices
Using nested lists as a matrix works for simple computational tasks, however, there is a better way of working with matrices in Python using NumPy package.
- NumPy Array
NumPy is a package for scientific computing which has support for a powerful N-dimensional array object. Before you can use NumPy, you need to install it. For more info,
- Visit: How to install NumPy?
- If you are on Windows, download and install anaconda distribution of Python. It comes with NumPy and other several packages related to data science and machine learning.
Once NumPy is installed, you can import and use it.
NumPy provides multidimensional array of numbers (which is actually an object). Let's take an example:
As you can see, NumPy's array class is called ndarray .
How to create a NumPy array?
There are several ways to create NumPy arrays.
1. Array of integers, floats and complex Numbers
When you run the program, the output will be:
2. Array of zeros and ones
Here, we have specified dtype to 32 bits (4 bytes). Hence, this array can take values from -2 -31 to 2 -31 -1 .
3. Using arange() and shape()
Learn more about other ways of creating a NumPy array .
Above, we gave you 3 examples: addition of two matrices, multiplication of two matrices and transpose of a matrix. We used nested lists before to write those programs. Let's see how we can do the same task using NumPy array.
Addition of Two Matrices
We use + operator to add corresponding elements of two NumPy matrices.
Multiplication of Two Matrices
To multiply two matrices, we use dot() method. Learn more about how numpy.dot works.
Note: * is used for array multiplication (multiplication of corresponding elements of two arrays) not matrix multiplication.
Transpose of a Matrix
We use numpy.transpose to compute transpose of a matrix.
As you can see, NumPy made our task much easier.
Access matrix elements, rows and columns
Access matrix elements
Similar like lists, we can access matrix elements using index. Let's start with a one-dimensional NumPy array.
Now, let's see how we can access elements of a two-dimensional array (which is basically a matrix).
Access rows of a Matrix
Access columns of a Matrix
If you don't know how this above code works, read slicing of a matrix section of this article.
Slicing of a Matrix
Slicing of a one-dimensional NumPy array is similar to a list. If you don't know how slicing for a list works, visit Understanding Python's slice notation .
Let's take an example:
Now, let's see how we can slice a matrix.
As you can see, using NumPy (instead of nested lists) makes it a lot easier to work with matrices, and we haven't even scratched the basics. We suggest you to explore NumPy package in detail especially if you trying to use Python for data science/analytics.
NumPy Resources you might find helpful:
- NumPy Tutorial
- NumPy Reference
Table of Contents
- What is a matrix?
- Numbers(integers, float, complex etc.) Array
- Zeros and Ones Array
- Array Using arange() and shape()
- Access elements
- Access rows
- Access columns
- Slicing of Matrix
- Useful Resources
Sorry about that.
- Free Python 3 Course
- Control Flow
- Exception Handling
- Python Programs
- Python Projects
- Python Interview Questions
- Python Database
- Data Science With Python
- Machine Learning with Python
- Explore Our Geeks Community
- Python program to search for the minimum element occurring consecutively n times in a matrix
- Python Program for Sum the digits of a given number
- Python Program That Prints Out the Decimal Equivalents of 1/2, 1/3, 1/4, . . . ,1/10
- Python program to print number of bits to store an integer and also the number in Binary format
- How to Convert PIL Image into pygame surface image?
- Python | Encoding Decoding using Matrix
- Python program to print the binary value of the numbers from 1 to N
- Python Program to Convert String Matrix Representation to Matrix
- Python | Type casting whole List and Matrix
- Python - Create nested list containing values as the count of list items
- Python - Convert Matrix to Coordinate Dictionary
- Python - Row with Minimum Sum in Matrix
- Python - Consecutive Row summation in Matrix
- How to format a string using a dictionary in Python
- Python - Initialize dictionary keys with Matrix
- Python - Summation Matrix columns
- Python program to convert integer to roman
- Python | Remove duplicates in Matrix
- Python Program to Reverse Every Kth row in a Matrix
Take Matrix input from user in Python
Matrix is nothing but a rectangular arrangement of data or numbers. In other words, it is a rectangular array of data or numbers. The horizontal entries in a matrix are called as ‘rows’ while the vertical entries are called as ‘columns’. If a matrix has r number of rows and c number of columns then the order of matrix is given by r x c . Each entries in a matrix can be integer values, or floating values, or even it can be complex numbers.
In Python, we can take a user input matrix in different ways. Some of the methods for user input matrix in Python are shown below:
Time complexity: O(RC) Auxiliary space: O(RC)
Code #2: Using map() function and Numpy. In Python, there exists a popular library called NumPy . This library is a fundamental library for any scientific computation. It is also used for multidimensional arrays and as we know matrix is a rectangular array, we will use this library for user input matrix.
Time complexity: O(RC), as the code iterates through RC elements to create the matrix. Auxiliary space: O(RC), as the code creates an RC sized matrix to store the entries.
Please Login to comment...
- Python matrix-program
Please write us at contrib[email protected] to report any issue with the above content
Improve your Coding Skills with Practice
It is no longer recommended to use this class, even for linear algebra. Instead use regular arrays. The class may be removed in the future.
Returns a matrix from an array-like object, or from a string of data. A matrix is a specialized 2-D array that retains its 2-D nature through operations. It has certain special operators, such as * (matrix multiplication) and ** (matrix power).
If data is a string, it is interpreted as a matrix with commas or spaces separating columns, and semicolons separating rows.
Data-type of the output matrix.
If data is already an ndarray , then this flag determines whether the data is copied (the default), or whether a view is constructed.
Return self as an ndarray object.
Return self as a flattened ndarray .
Returns the (complex) conjugate transpose of self .
Returns the (multiplicative) inverse of invertible self .
Returns the transpose of the matrix.
Base object if memory is from some other object.
An object to simplify the interaction of the array with the ctypes module.
Python buffer object pointing to the start of the array’s data.
Data-type of the array’s elements.
Information about the memory layout of the array.
A 1-D iterator over the array.
The imaginary part of the array.
Length of one array element in bytes.
Total bytes consumed by the elements of the array.
Number of array dimensions.
The real part of the array.
Tuple of array dimensions.
Number of elements in the array.
Tuple of bytes to step in each dimension when traversing an array.
- Python Data Structure and Algorithms Tutorial
- Python - DS Home
- Python - DS Introduction
- Python - DS Environment
- Python - Arrays
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - 2-D Array
Python - Matrix
- Python - Sets
- Python - Maps
- Python - Linked Lists
- Python - Stack
- Python - Queue
- Python - Dequeue
- Python - Advanced Linked list
- Python - Hash Table
- Python - Binary Tree
- Python - Search Tree
- Python - Heaps
- Python - Graphs
- Python - Algorithm Design
- Python - Divide and Conquer
- Python - Recursion
- Python - Backtracking
- Python - Sorting Algorithms
- Python - Searching Algorithms
- Python - Graph Algorithms
- Python - Algorithm Analysis
- Python - Big-O Notation
- Python - Algorithm Classes
- Python - Amortized Analysis
- Python - Algorithm Justifications
- Python Data Structure & Algorithms Useful Resources
- Python - Quick Guide
- Python - Useful Resources
- Python - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
Matrix is a special case of two dimensional array where each data element is of strictly same size. So every matrix is also a two dimensional array but not vice versa.
Matrices are very important data structures for many mathematical and scientific calculations. As we have already discussed two dimnsional array data structure in the previous chapter we will be focusing on data structure operations specific to matrices in this chapter.
We also be using the numpy package for matrix data manipulation.
Consider the case of recording temprature for 1 week measured in the morning, mid-day, evening and mid-night. It can be presented as a 7X5 matrix using an array and the reshape method available in numpy.
The above data can be represented as a two dimensional array as below −
The data elements in a matrix can be accessed by using the indexes. The access method is same as the way data is accessed in Two dimensional array.
When the above code is executed, it produces the following result −
Adding a row
Use the below mentioned code to add a row in a matrix.
Adding a column
We can add column to a matrix using the insert() method. here we have to mention the index where we want to add the column and a array containing the new values of the columns added.In the below example we add t a new column at the fifth position from the beginning.
Delete a row
We can delete a row from a matrix using the delete() method. We have to specify the index of the row and also the axis value which is 0 for a row and 1 for a column.
Delete a column
We can delete a column from a matrix using the delete() method. We have to specify the index of the column and also the axis value which is 0 for a row and 1 for a column.
Update a row
To update the values in the row of a matrix we simply re-assign the values at the index of the row. In the below example all the values for thrusday's data is marked as zero. The index for this row is 3.
Kickstart Your Career
Get certified by completing the course
Software Developer & Professional Explainer
NumPy Indexing and Assignment
Hey - Nick here! This page is a free excerpt from my $199 course Python for Finance, which is 50% off for the next 50 students.
If you want the full course, click here to sign up.
In this lesson, we will explore indexing and assignment in NumPy arrays.
The Array I'll Be Using In This Lesson
As before, I will be using a specific array through this lesson. This time it will be generated using the np.random.rand method. Here's how I generated the array:
Here is the actual array:
To make this array easier to look at, I will round every element of the array to 2 decimal places using NumPy's round method:
Here's the new array:
How To Return A Specific Element From A NumPy Array
We can select (and return) a specific element from a NumPy array in the same way that we could using a normal Python list: using square brackets.
An example is below:
We can also reference multiple elements of a NumPy array using the colon operator. For example, the index [2:] selects every element from index 2 onwards. The index [:3] selects every element up to and excluding index 3. The index [2:4] returns every element from index 2 to index 4, excluding index 4. The higher endpoint is always excluded.
A few example of indexing using the colon operator are below.
Element Assignment in NumPy Arrays
We can assign new values to an element of a NumPy array using the = operator, just like regular python lists. A few examples are below (note that this is all one code block, which means that the element assignments are carried forward from step to step).
arr[2:5] = 0.5
Returns array([0. , 0. , 0.5, 0.5, 0.5])
As you can see, modifying second_new_array also changed the value of new_array .
Why is this?
By default, NumPy does not create a copy of an array when you reference the original array variable using the = assignment operator. Instead, it simply points the new variable to the old variable, which allows the second variable to make modification to the original variable - even if this is not your intention.
This may seem bizarre, but it does have a logical explanation. The purpose of array referencing is to conserve computing power. When working with large data sets, you would quickly run out of RAM if you created a new array every time you wanted to work with a slice of the array.
Fortunately, there is a workaround to array referencing. You can use the copy method to explicitly copy a NumPy array.
An example of this is below.
As you can see below, making modifications to the copied array does not alter the original.
So far in the lesson, we have only explored how to reference one-dimensional NumPy arrays. We will now explore the indexing of two-dimensional arrays.
Indexing Two-Dimensional NumPy Arrays
To start, let's create a two-dimensional NumPy array named mat :
There are two ways to index a two-dimensional NumPy array:
- mat[row, col]
I personally prefer to index using the mat[row][col] nomenclature because it is easier to visualize in a step-by-step fashion. For example:
You can also generate sub-matrices from a two-dimensional NumPy array using this notation:
Array referencing also applies to two-dimensional arrays in NumPy, so be sure to use the copy method if you want to avoid inadvertently modifying an original array after saving a slice of it into a new variable name.
Conditional Selection Using NumPy Arrays
NumPy arrays support a feature called conditional selection , which allows you to generate a new array of boolean values that state whether each element within the array satisfies a particular if statement.
An example of this is below (I also re-created our original arr variable since its been awhile since we've seen it):
You can also generate a new array of values that satisfy this condition by passing the condition into the square brackets (just like we do for indexing).
An example of this is below:
Conditional selection can become significantly more complex than this. We will explore more examples in this section's associated practice problems.
In this lesson, we explored NumPy array indexing and assignment in thorough detail. We will solidify your knowledge of these concepts further by working through a batch of practice problems in the next section.
Machine Learning with Python Cookbook by Chris Albon
Get full access to Machine Learning with Python Cookbook and 60K+ other titles, with a free 10-day trial of O'Reilly.
There are also live events, courses curated by job role, and more.
Chapter 1. Vectors, Matrices, and Arrays
NumPy is the foundation of the Python machine learning stack. NumPy allows for efficient operations on the data structures often used in machine learning: vectors, matrices, and tensors. While NumPy is not the focus of this book, it will show up frequently throughout the following chapters. This chapter covers the most common NumPy operations we are likely to run into while working on machine learning workflows.
1.1 Creating a Vector
You need to create a vector.
Use NumPy to create a one-dimensional array:
NumPy’s main data structure is the multidimensional array. To create a vector, we simply create a one-dimensional array. Just like vectors, these arrays can be represented horizontally (i.e., rows) or vertically (i.e., columns).
Vectors, Math Is Fun
Euclidean vector, Wikipedia
1.2 Creating a Matrix
You need to create a matrix.
Use NumPy to create a two-dimensional array:
To create a matrix we can use a NumPy two-dimensional array. In our solution, the matrix contains three rows and two columns (a column of 1s and a column of 2s).
NumPy actually has a dedicated matrix data structure:
However, the matrix data structure is not recommended for two reasons. First, arrays are the de facto standard data structure of NumPy. Second, the vast majority of NumPy operations return arrays, not matrix objects.
Matrix, Wolfram MathWorld
1.3 Creating a Sparse Matrix
Given data with very few nonzero values, you want to efficiently represent it.
Create a sparse matrix:
A frequent situation in machine learning is having a huge amount of data; however, most of the elements in the data are zeros. For example, imagine a matrix where the columns are every movie on Netflix, the rows are every Netflix user, and the values are how many times a user has watched that particular movie. This matrix would have tens of thousands of columns and millions of rows! However, since most users do not watch most movies, the vast majority of elements would be zero.
Sparse matrices only store nonzero elements and assume all other values will be zero, leading to significant computational savings. In our solution, we created a NumPy array with two nonzero values, then converted it into a sparse matrix. If we view the sparse matrix we can see that only the nonzero values are stored:
There are a number of types of sparse matrices. However, in compressed sparse row (CSR) matrices, (1, 1) and (2, 0) represent the (zero-indexed) indices of the non-zero values 1 and 3 , respectively. For example, the element 1 is in the second row and second column. We can see the advantage of sparse matrices if we create a much larger matrix with many more zero elements and then compare this larger matrix with our original sparse matrix:
As we can see, despite the fact that we added many more zero elements in the larger matrix, its sparse representation is exactly the same as our original sparse matrix. That is, the addition of zero elements did not change the size of the sparse matrix.
As mentioned, there are many different types of sparse matrices, such as compressed sparse column, list of lists, and dictionary of keys. While an explanation of the different types and their implications is outside the scope of this book, it is worth noting that while there is no “best” sparse matrix type, there are meaningful differences between them and we should be conscious about why we are choosing one type over another.
Sparse matrices, SciPy documentation
101 Ways to Store a Sparse Matrix
1.4 Selecting Elements
You need to select one or more elements in a vector or matrix.
NumPy’s arrays make that easy:
Like most things in Python, NumPy arrays are zero-indexed, meaning that the index of the first element is 0, not 1. With that caveat, NumPy offers a wide variety of methods for selecting (i.e., indexing and slicing) elements or groups of elements in arrays:
1.5 Describing a Matrix
You want to describe the shape, size, and dimensions of the matrix.
Use shape , size , and ndim :
This might seem basic (and it is); however, time and again it will be valuable to check the shape and size of an array both for further calculations and simply as a gut check after some operation.
1.6 Applying Operations to Elements
You want to apply some function to multiple elements in an array.
Use NumPy’s vectorize :
NumPy’s vectorize class converts a function into a function that can apply to all elements in an array or slice of an array. It’s worth noting that vectorize is essentially a for loop over the elements and does not increase performance. Furthermore, NumPy arrays allow us to perform operations between arrays even if their dimensions are not the same (a process called broadcasting ). For example, we can create a much simpler version of our solution using broadcasting:
1.7 Finding the Maximum and Minimum Values
You need to find the maximum or minimum value in an array.
Use NumPy’s max and min :
Often we want to know the maximum and minimum value in an array or subset of an array. This can be accomplished with the max and min methods. Using the axis parameter we can also apply the operation along a certain axis:
1.8 Calculating the Average, Variance, and Standard Deviation
You want to calculate some descriptive statistics about an array.
Use NumPy’s mean , var , and std :
Just like with max and min , we can easily get descriptive statistics about the whole matrix or do calculations along a single axis:
1.9 Reshaping Arrays
You want to change the shape (number of rows and columns) of an array without changing the element values.
Use NumPy’s reshape :
reshape allows us to restructure an array so that we maintain the same data but it is organized as a different number of rows and columns. The only requirement is that the shape of the original and new matrix contain the same number of elements (i.e., the same size). We can see the size of a matrix using size :
One useful argument in reshape is -1 , which effectively means “as many as needed,” so reshape(1, -1) means one row and as many columns as needed:
Finally, if we provide one integer, reshape will return a 1D array of that length:
1.10 Transposing a Vector or Matrix
You need to transpose a vector or matrix.
Use the T method:
Transposing is a common operation in linear algebra where the column and row indices of each element are swapped. One nuanced point that is typically overlooked outside of a linear algebra class is that, technically, a vector cannot be transposed because it is just a collection of values:
However, it is common to refer to transposing a vector as converting a row vector to a column vector (notice the second pair of brackets) or vice versa:
1.11 Flattening a Matrix
You need to transform a matrix into a one-dimensional array.
Use flatten :
flatten is a simple method to transform a matrix into a one-dimensional array. Alternatively, we can use reshape to create a row vector:
1.12 Finding the Rank of a Matrix
You need to know the rank of a matrix.
Use NumPy’s linear algebra method matrix_rank :
The rank of a matrix is the dimensions of the vector space spanned by its columns or rows. Finding the rank of a matrix is easy in NumPy thanks to matrix_rank .
The Rank of a Matrix, CliffsNotes
1.13 Calculating the Determinant
You need to know the determinant of a matrix.
Use NumPy’s linear algebra method det :
It can sometimes be useful to calculate the determinant of a matrix. NumPy makes this easy with det .
The determinant | Essence of linear algebra, chapter 5, 3Blue1Brown
Determinant, Wolfram MathWorld
1.14 Getting the Diagonal of a Matrix
You need to get the diagonal elements of a matrix.
Use diagonal :
NumPy makes getting the diagonal elements of a matrix easy with diagonal . It is also possible to get a diagonal off from the main diagonal by using the offset parameter:
1.15 Calculating the Trace of a Matrix
You need to calculate the trace of a matrix.
Use trace :
The trace of a matrix is the sum of the diagonal elements and is often used under the hood in machine learning methods. Given a NumPy multidimensional array, we can calculate the trace using trace . We can also return the diagonal of a matrix and calculate its sum:
The Trace of a Square Matrix
1.16 Finding Eigenvalues and Eigenvectors
You need to find the eigenvalues and eigenvectors of a square matrix.
Use NumPy’s linalg.eig :
Eigenvectors are widely used in machine learning libraries. Intuitively, given a linear transformation represented by a matrix, A , eigenvectors are vectors that, when that transformation is applied, change only in scale (not direction). More formally:
where A is a square matrix, λ contains the eigenvalues and v contains the eigenvectors. In NumPy’s linear algebra toolset, eig lets us calculate the eigenvalues, and eigenvectors of any square matrix.
Eigenvectors and Eigenvalues Explained Visually, Setosa.io
Eigenvectors and eigenvalues | Essence of linear algebra, Chapter 10, 3Blue1Brown
1.17 Calculating Dot Products
You need to calculate the dot product of two vectors.
Use NumPy’s dot :
The dot product of two vectors, a and b , is defined as:
where a i is the i th element of vector a . We can use NumPy’s dot function to calculate the dot product. Alternatively, in Python 3.5+ we can use the new @ operator:
Vector dot product and vector length, Khan Academy
Dot Product, Paul’s Online Math Notes
1.18 Adding and Subtracting Matrices
You want to add or subtract two matrices.
Use NumPy’s add and subtract :
Alternatively, we can simply use the + and - operators:
1.19 Multiplying Matrices
You want to multiply two matrices.
Alternatively, in Python 3.5+ we can use the @ operator:
If we want to do element-wise multiplication, we can use the * operator:
Array vs. Matrix Operations, MathWorks
1.20 Inverting a Matrix
You want to calculate the inverse of a square matrix.
Use NumPy’s linear algebra inv method:
The inverse of a square matrix, A , is a second matrix A –1 , such that:
where I is the identity matrix. In NumPy we can use linalg.inv to calculate A –1 if it exists. To see this in action, we can multiply a matrix by its inverse and the result is the identity matrix:
Inverse of a Matrix
1.21 Generating Random Values
You want to generate pseudorandom values.
Use NumPy’s random :
NumPy offers a wide variety of means to generate random numbers, many more than can be covered here. In our solution we generated floats; however, it is also common to generate integers:
Alternatively, we can generate numbers by drawing them from a distribution:
Finally, it can sometimes be useful to return the same random numbers multiple times to get predictable, repeatable results. We can do this by setting the “seed” (an integer) of the pseudorandom generator. Random processes with the same seed will always produce the same output. We will use seeds throughout this book so that the code you see in the book and the code you run on your computer produces the same results.
Get Machine Learning with Python Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.
Don’t leave empty-handed
Get Mark Richards’s Software Architecture Patterns ebook to better understand how to design components—and how they should interact.
It’s yours, free.
Check it out now on O’Reilly
Dive in for free with a 10-day trial of the O’Reilly learning platform—then explore all the other resources our members count on to build skills and solve problems every day.
Python oops, python mysql, python mongodb, python sqlite, python questions, python tkinter (gui), python web blocker, related tutorials, python programs.
- Send your Feedback to [email protected]
Help Others, Please Share
Learn Latest Tutorials
Python Design Patterns
B.Tech / MCA
JavaTpoint offers too many high quality services. Mail us on h [email protected] , to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- Graphic Designing
- Digital Marketing
- On Page and Off Page SEO
- Content Development
- Corporate Training
- Classroom and Online Training
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected] . Duration: 1 week to 2 week