SoFunction
Updated on 2025-03-02

The process of converting original edge list into an adjacency matrix using Python

In graph theory and network analysis, a graph is a very important data structure, which consists of nodes (or vertices) and edges connecting these nodes. In Python, we can use an adjacency matrix to represent the graph, where the rows and columns of the matrix represent nodes, and the values ​​in the matrix indicate whether there are edges between nodes.

Sometimes, we get the original list of edges from external data sources, and we need to convert it into an adjacency matrix for subsequent analysis and processing. This article will explain how to use Python to implement this transformation process.

Original edge list

Suppose we have a list of original edges where each element represents an edge, for example:

edges = [(0, 1), (0, 2), (1, 2), (2, 3)]

In this example, each tuple(a, b)Represents nodeaand nodesbThere is an edge between them.

Convert to adjacency matrix

We first need to determine the number of nodes in the graph and then create a zero matrix of corresponding size. Next, we traverse the original edge list and set the corresponding matrix element to 1 according to the two nodes of each edge. The final matrix is ​​the adjacency matrix we need.

Let's see how to implement this process with Python code:

def edges_to_adjacency_matrix(edges):
    # Find the number of nodes in the graph    max_node = max(max(edge) for edge in edges) + 1
    
    # Create a zero matrix    adjacency_matrix = [[0] * max_node for _ in range(max_node)]
    
    # traverse the original edge list and update the adjacency matrix    for edge in edges:
        adjacency_matrix[edge[0]][edge[1]] = 1
        adjacency_matrix[edge[1]][edge[0]] = 1  # If it is an undirected graph, the edge is two-way    
    return adjacency_matrix

# testedges = [(0, 1), (0, 2), (1, 2), (2, 3)]
adjacency_matrix = edges_to_adjacency_matrix(edges)
for row in adjacency_matrix:
    print(row)

In this code,edges_to_adjacency_matrixThe function accepts the original edge list as a parameter and returns the corresponding adjacency matrix. We then test the given edge list and output the generated adjacency matrix.

Extend and optimize

Although the above code can complete the conversion of the original edge list to the adjacency matrix, some extensions and optimizations may be required in practical applications.

  1. Process directed and undirected graphs: The current code processes undirected graphs by default. If it is a directed graph, the code needs to be modified according to specific needs and only set the adjacency relationship in one direction.

  2. Process weights: Sometimes edges are not only a relationship of existence or not, but may also have weight. Modify the code to support weighted graphs.

  3. Using sparse matrix: For large graphs, adjacency matrix may occupy a lot of memory, so you can consider using sparse matrix to save memory space.

  4. Performance optimization: For large-scale edge lists, the performance of the code needs to be considered. You can try to implement the transformation process using more efficient data structures or algorithms.

Here are some optimization examples of the code:

import numpy as np

def edges_to_adjacency_matrix(edges, directed=False):
    max_node = max(max(edge) for edge in edges) + 1
    adjacency_matrix = ((max_node, max_node))
    for edge in edges:
        if directed:
            adjacency_matrix[edge[0]][edge[1]] = 1
        else:
            adjacency_matrix[edge[0]][edge[1]] = 1
            adjacency_matrix[edge[1]][edge[0]] = 1
    return adjacency_matrix

# testedges = [(0, 1), (0, 2), (1, 2), (2, 3)]
adjacency_matrix = edges_to_adjacency_matrix(edges)
print("Adjacent Matrix of Undirected Graphs:")
print(adjacency_matrix)

directed_edges = [(0, 1), (0, 2), (1, 2), (2, 3)]
directed_adjacency_matrix = edges_to_adjacency_matrix(directed_edges, directed=True)
print("\nAdjacent Matrix of Directed Graphs:")
print(directed_adjacency_matrix)

In the optimized code, we use the NumPy library to create and manipulate the matrix, which can improve the performance and readability of the code. At the same time, we added a parameterdirectedTo indicate the type of the graph, thus supporting the conversion of directed and undirected graphs.

Optimize memory footprint using sparse matrix

When working with large graphs, the adjacency matrix can become very sparse, with most elements being zero. To optimize memory footprint, sparse matrices can be used to represent adjacency relationships.

There are a variety of libraries in Python that can handle sparse matrices, and the Scipy library provides various operations and algorithms for sparse matrices. Let's see how to optimize the code using sparse matrix in Scipy:

import numpy as np
from  import lil_matrix

def edges_to_adjacency_matrix(edges, directed=False):
    max_node = max(max(edge) for edge in edges) + 1
    adjacency_matrix = lil_matrix((max_node, max_node), dtype=np.int8)
    for edge in edges:
        if directed:
            adjacency_matrix[edge[0], edge[1]] = 1
        else:
            adjacency_matrix[edge[0], edge[1]] = 1
            adjacency_matrix[edge[1], edge[0]] = 1
    return adjacency_matrix

# testedges = [(0, 1), (0, 2), (1, 2), (2, 3)]
adjacency_matrix = edges_to_adjacency_matrix(edges)
print("Adjacent Matrix of Undirected Graphs:")
print(adjacency_matrix.toarray())

directed_edges = [(0, 1), (0, 2), (1, 2), (2, 3)]
directed_adjacency_matrix = edges_to_adjacency_matrix(directed_edges, directed=True)
print("\nAdjacent Matrix of Directed Graphs:")
print(directed_adjacency_matrix.toarray())

In this version of the code, we used.lil_matrixTo create sparse matrix. It can effectively handle large sparse matrices and store only non-zero elements, thus saving memory.

With this optimization, we can handle larger-scale graph data without the problem of performance degradation or insufficient memory due to excessive memory usage.

Handle the list of edges with weights

In some cases, the edges of the graph not only represent the connection relationship between nodes, but may also have weight information. For example, in a traffic network, edges may represent roads, and weights may represent length or time of travel of roads.

Let's see how to modify the code to support a list of edges with weights:

import numpy as np
from  import lil_matrix

def edges_to_adjacency_matrix(edges, directed=False, weighted=False):
    max_node = max(max(edge[0], edge[1]) for edge in edges) + 1
    adjacency_matrix = lil_matrix((max_node, max_node), dtype=np.float32)
    for edge in edges:
        if directed:
            if weighted:
                adjacency_matrix[edge[0], edge[1]] = edge[2]
            else:
                adjacency_matrix[edge[0], edge[1]] = 1
        else:
            if weighted:
                adjacency_matrix[edge[0], edge[1]] = edge[2]
                adjacency_matrix[edge[1], edge[0]] = edge[2]
            else:
                adjacency_matrix[edge[0], edge[1]] = 1
                adjacency_matrix[edge[1], edge[0]] = 1
    return adjacency_matrix

# testweighted_edges = [(0, 1, 5), (0, 2, 3), (1, 2, 2), (2, 3, 7)]
weighted_adjacency_matrix = edges_to_adjacency_matrix(weighted_edges, weighted=True)
print("Adjacent matrix with weights:")
print(weighted_adjacency_matrix.toarray())

In this version of the code, we added a weighted parameter to indicate whether the edges have weights. If the weighted parameter is True, the weight information is extracted from the edge list and saved to the adjacency matrix. Otherwise, the values ​​in the adjacency matrix still indicate the existence or absence of an edge.

With this modification, we can process graph data with weight information and retain this information in the adjacency matrix for subsequent analysis and calculations.

Visualization of the diagram

When working with graph data, visualization is a powerful tool that helps us intuitively understand the structure and features of graphs. There are many libraries in Python that can be used to visualize graph data. NetworkX is a commonly used library that provides rich functions to create, manipulate and visualize graphs.

Let's see how to use NetworkX to visualize our generated adjacency matrix:

import networkx as nx
import  as plt

def visualize_adjacency_matrix(adjacency_matrix):
    G = nx.from_numpy_matrix(adjacency_matrix)
    pos = nx.spring_layout(G)  # Define node location    (G, pos, with_labels=True, node_color='skyblue', node_size=500, font_size=10)  # Draw a picture    edge_labels = {(i, j): w['weight'] for i, j, w in (data=True)}  # Get edge weights    nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=10)  # Draw edge weights    ("Graph Visualization")
    ()

# testweighted_edges = [(0, 1, 5), (0, 2, 3), (1, 2, 2), (2, 3, 7)]
weighted_adjacency_matrix = edges_to_adjacency_matrix(weighted_edges, weighted=True)
print("Adjacent matrix with weights:")
print(weighted_adjacency_matrix.toarray())

visualize_adjacency_matrix(weighted_adjacency_matrix.toarray())

In this code, we first use NetworkX's from_numpy_matrix function to convert the adjacency matrix into a graph object. Then use spring_layout to define the position of the node and draw the plot using the draw function. Finally, we use the draw_networkx_edge_labels function to draw the weight of the edges.

Through visualization, we can clearly see the structure of the graph and intuitively understand the connection relationship and weight information between nodes.

Convert adjacency matrix to original edge list

In graph data processing, sometimes we need to convert the adjacency matrix back to the original edge list form. This may be useful in some algorithms and applications, as some may be more suitable for using edge lists to represent graphs.

Let's see how to write code to implement this transformation:

import numpy as np

def adjacency_matrix_to_edges(adjacency_matrix):
    edges = []
    for i in range(adjacency_matrix.shape[0]):
        for j in range(adjacency_matrix.shape[1]):
            if adjacency_matrix[i, j] != 0:
                ((i, j, adjacency_matrix[i, j]))
    return edges

# testadjacency_matrix = ([[0, 1, 0, 0],
                              [1, 0, 1, 0],
                              [0, 1, 0, 1],
                              [0, 0, 1, 0]], dtype=np.float32)
print("Original adjacency matrix:")
print(adjacency_matrix)

edges = adjacency_matrix_to_edges(adjacency_matrix)
print("\nConverted edge list:")
print(edges)

In this code, we iterate through each element of the adjacency matrix and convert the element into an edge in the edge list if the value of the element is not zero. For weighted graphs, we also save the weight information in the edge list.

Through this conversion process, we can convert the graph represented by the adjacency matrix into an edge list form, which facilitates the implementation and application of some algorithms.

Summary and prospect

This article introduces how to convert the original edge list into an adjacency matrix using Python, and performs a series of extensions and optimizations to meet the needs of different scenarios. We cover multiple aspects of graph data processing from processing undirected and directed graphs, weighted edge lists, to using sparse matrix to optimize memory usage, to converting graph visualization and adjacency matrix into original edge lists.

In practical applications, graph data processing is a very important and widely used field, involving many fields such as network analysis, social networks, traffic planning, and bioinformatics. Mastering the skills of graph data processing can help us better understand and analyze complex data structures, thereby solving practical problems.

In the future, with the continuous increase in data scale and increase in complexity, the field of graph data processing will face more challenges and opportunities. We can expect more efficient, flexible and feature-rich tools and algorithms to address changing needs and challenges. At the same time, we can continue to learn and explore, continuously improve our ability and level in the field of graph data processing, and make greater contributions to solving practical problems.

I hope this article will be helpful to you in understanding and applying graph data processing. You are also welcome to further study and explore this field in depth and contribute to the development of data science and engineering.

The above is the detailed content of the process of using Python to convert the original edge list into an adjacency matrix. For more information about converting Python edge list to an adjacency matrix, please pay attention to my other related articles!