Create a Matrix in Python

While working on a data analysis project, I needed to handle two-dimensional data efficiently. The solution? Python matrices! Whether you’re building a machine learning model, solving a system of equations, or analyzing data, matrices are essential tools in Python programming.

In this article, I’ll cover five simple ways to create matrices in Python, from using built-in lists to specialized libraries like NumPy and pandas.

So let’s dive in!

Create a Matrix in Python

Let me show you how to create a matrix in Python using various methods, along with suitable examples.

Read NumPy Normalize 0 and 1 in Python

Method 1 – Use Nested Lists

Creating matrices with Python’s built-in lists is the simplest approach for beginners.

Here’s how to create a simple 3×3 matrix:

# Creating a 3x3 matrix using nested lists
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Accessing elements
print(matrix[0][0]) 
print(matrix[1][2])   

# Printing the entire matrix
for row in matrix:
    print(row)

Output:

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

You can see the output in the screenshot below.

python matrix

This method is simple but has limitations. Operations like matrix multiplication aren’t built-in, and you’ll need to write your functions for that.

Check out Create a 2D NumPy Array in Python

Method 2 – Use NumPy Arrays

NumPy is the gold standard for numerical computing in Python, offering efficient features for matrix operations.

First, install NumPy if you haven’t already:

pip install numpy

Here’s how to create matrices with NumPy:

import numpy as np

# Creating a matrix from a list
matrix1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(matrix1)

# Creating a matrix of zeros
zeros_matrix = np.zeros((3, 3))
print(zeros_matrix)

# Creating a matrix of ones
ones_matrix = np.ones((3, 3))
print(ones_matrix)

# Creating an identity matrix
identity_matrix = np.eye(3)
print(identity_matrix)

# Creating a matrix with random values
random_matrix = np.random.rand(3, 3)
print(random_matrix)

You can see the output in the screenshot below.

matrix in python

The real power of NumPy matrices comes with operations:

import numpy as np

# Creating two matrices
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])

# Matrix addition
print(a + b)

# Matrix multiplication
print(np.dot(a, b))
# Or using the @ operator (Python 3.5+)
print(a @ b)

# Matrix transpose
print(a.T)

# Matrix determinant
print(np.linalg.det(a))

If you’re working with numerical data, NumPy is almost always the way to go.

Read NumPy Unique Function in Python

Method 3 – Use pandas DataFrames

When your matrix represents tabular data with row and column labels, pandas DataFrames are excellent.

First, install pandas:

pip install pandas

Here’s how to create a matrix using pandas:

import pandas as pd
import numpy as np

# Creating a DataFrame from a NumPy array
data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
df = pd.DataFrame(data, columns=['A', 'B', 'C'], index=['Row1', 'Row2', 'Row3'])

print(df)

# Accessing elements
print(df.loc['Row1', 'A']) 
print(df.iloc[0, 0])        

# DataFrame operations
print(df.mean())  # Column means
print(df.sum())   # Column sums

You can see the output in the screenshot below.

matrix python

I’ve found pandas particularly useful when working with data that needs labeling or when I need to perform data analysis tasks like filtering or aggregation.

Check out np.unit8 in Python

Method 4 – Use SciPy Sparse Matrices

When dealing with large matrices where most elements are zero (sparse matrices), SciPy’s sparse module is much more memory-efficient.

Install SciPy if needed:

pip install scipy

Here’s how to create sparse matrices:

from scipy import sparse

# Creating a sparse matrix (Coordinate format)
# Format: sparse.coo_matrix((data, (row_indices, col_indices)), shape=(rows, cols))
row_indices = [0, 1, 2, 0]
col_indices = [0, 1, 2, 2]
data = [1, 2, 3, 4]
sparse_matrix = sparse.coo_matrix((data, (row_indices, col_indices)), shape=(3, 3))

print(sparse_matrix)
# Convert to dense matrix to view all elements
print(sparse_matrix.toarray())

# Other sparse formats
csr_matrix = sparse.csr_matrix(sparse_matrix)  # Compressed Sparse Row format
csc_matrix = sparse.csc_matrix(sparse_matrix)  # Compressed Sparse Column format

I’ve used this approach when building recommendation systems where the user-item interaction matrix was extremely sparse.

Read NumPy Divide Array by Scalar in Python

Method 5 – Use SymPy for Symbolic Matrices

For mathematical operations where you need symbolic computation rather than numerical values, SymPy is the way to go.

Install SymPy:

pip install sympy

Here’s how to create symbolic matrices:

import sympy as sp

# Define symbolic variables
x, y, z = sp.symbols('x y z')

# Create a symbolic matrix
symbolic_matrix = sp.Matrix([
    [x, y, z],
    [y, z, x],
    [z, x, y]
])

print(symbolic_matrix)

# Matrix operations
determinant = symbolic_matrix.det()
print(f"Determinant: {determinant}")

inverse = symbolic_matrix.inv()
print(f"Inverse: {inverse}")

eigenvals = symbolic_matrix.eigenvals()
print(f"Eigenvalues: {eigenvals}")

This method is particularly useful when working on mathematical proofs or when you need to solve equations symbolically.

Check out Copy a NumPy Array to the Clipboard through Python

Real-World Application: Stock Portfolio Analysis

Let’s put our matrix knowledge to work with a practical example, analyzing a portfolio of popular US stocks:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Example stock price data (simplified)
# Rows: Days, Columns: Stocks (Apple, Microsoft, Google)
stock_prices = np.array([
    [150.25, 290.15, 2680.70],  # Day 1
    [152.75, 292.85, 2695.45],  # Day 2
    [151.80, 291.20, 2700.35],  # Day 3
    [153.65, 295.30, 2710.65],  # Day 4
    [155.20, 297.45, 2725.80]   # Day 5
])

# Create a DataFrame for better visualization
stocks_df = pd.DataFrame(
    stock_prices, 
    columns=['AAPL', 'MSFT', 'GOOGL'],
    index=pd.date_range('2023-01-01', periods=5, freq='D')
)

print(stocks_df)

# Calculate daily returns
daily_returns = stocks_df.pct_change().dropna()
print("\nDaily Returns:")
print(daily_returns)

# Calculate correlation matrix
correlation_matrix = daily_returns.corr()
print("\nCorrelation Matrix:")
print(correlation_matrix)

# Visualize correlation matrix
plt.figure(figsize=(8, 6))
plt.imshow(correlation_matrix, cmap='coolwarm')
plt.colorbar()
plt.xticks(range(len(correlation_matrix.columns)), correlation_matrix.columns)
plt.yticks(range(len(correlation_matrix.columns)), correlation_matrix.columns)
plt.title('Stock Correlation Matrix')
plt.savefig('correlation_matrix.png')

This example showcases how we can analyze relationships between different stocks using matrices and visualization.

Read Convert the DataFrame to a NumPy Array Without Index in Python

Choose the Right Matrix Method

After years of working with Python, I’ve found that each matrix method has its place:

  • Nested Lists: Great for simple, small matrices when you’re getting started
  • NumPy Arrays: Perfect for numerical computations and mathematical operations
  • Pandas DataFrames: Ideal for labeled data and data analysis tasks
  • SciPy Sparse Matrices: Essential for large, sparse matrices to save memory
  • SymPy Matrices: Best for symbolic mathematics and equation solving

The best approach depends on your specific needs – consider what operations you’ll perform on your matrices and choose accordingly.

I hope you found this article helpful. In this tutorial, I have explained to you the methods to create a matrix in Python using nested lists, numpy arrays, pandas dataframes, scipy sparse matrices, sympy for portfolio analysis, and sympy for symbolic matrices. I also covered real-world applications and choosing the right matrix method.

You may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.