Thursday, November 12, 2026

From NumPy to NetworkX: Building Graphs From an Adjacency Matrix

TL;DR

This guide turns a NumPy adjacency matrix of transit stations into a NetworkX graph with one call, then finds the fastest route and the stations the network depends on. It also covers the details that trip people up: labels, weights, direction and what a zero means. You could write the search by hand, but NetworkX would rather do it for you.

Quick routes through the guide:

Say you have a NumPy array of travel times between five transit stations. A zero means there is no direct line. You want the fastest route from the airport to the stadium, and you want to know which stations the network depends on. You could write that search by hand. Or you could hand the array to NetworkX.

An adjacency matrix is a square array where the value in row i, column j describes the link from node i to node j. NetworkX turns that array into a graph with one call, networkx.from_numpy_array, and from there you get shortest paths, centrality and dozens of other graph algorithms. This guide walks through the conversion and the details that trip people up (node labels, weights, direction and zeros), with real output from NetworkX 3.7 and NumPy 2.5.

Key Takeaways

  • nx.from_numpy_array(A) builds a graph from a square NumPy array. Nonzero entries become edges, and their values are stored in the weight attribute.
  • Pass nodelist= to name the nodes in row order. Without it, nodes are numbered 0 to n−1.
  • The default result is an undirected Graph. Pass create_using=nx.DiGraph when entry (i, j) means a one-way link from i to j.
  • Zeros mean “no edge” by default. In NetworkX 3.7 the nonedge argument lets you pick a different marker, such as nan, if a zero weight is real.
  • nx.to_numpy_array converts back, so you can move between matrix math and graph algorithms.

Step 1: Start With an Adjacency Matrix

Here is the station network. Each value is the travel time in minutes on a direct line.

import numpy as np
import networkx as nx

stations = ["Airport", "Central", "Harbor", "Museum", "Stadium"]

# Travel minutes between stations; 0 means no direct line.
A = np.array([
    [0, 12,  0,  0,  0],
    [12, 0,  6,  4,  0],
    [0,  6,  0,  5,  9],
    [0,  4,  5,  0,  0],
    [0,  0,  9,  0,  0],
])

print("Symmetric:", np.array_equal(A, A.T))
Symmetric: True

Check symmetry before you choose a graph type. A symmetric matrix means every line runs both ways at the same cost, so an undirected graph fits. If A is not symmetric and you build an undirected graph anyway, NetworkX keeps only one of the two values for each pair (in our test, the one from the lower triangle), and you may not notice.

Step 2: Convert It With from_numpy_array

G = nx.from_numpy_array(A, nodelist=stations)
print(G)
print(list(G.edges(data="weight")))
Graph with 5 nodes and 5 edges
[('Airport', 'Central', 12), ('Central', 'Harbor', 6), ('Central', 'Museum', 4), ('Harbor', 'Museum', 5), ('Harbor', 'Stadium', 9)]

The 25 cells became 5 edges: the matrix has 10 nonzero values, and each undirected line appears twice (once above and once below the diagonal). The nodelist argument, added in NetworkX 3.4, maps row 0 to “Airport”, row 1 to “Central” and so on. On older versions, call nx.relabel_nodes(G, dict(enumerate(stations))) after building the graph.

The full signature is in the from_numpy_array reference. Two arguments are worth knowing: edge_attr renames the stored attribute (set it to None to treat the matrix as present or absent only), and parallel_edges controls how integer values become repeated edges in a multigraph.

Step 3: Run Graph Algorithms

Now the questions from the opening are one line each.

print("Degree:", dict(G.degree()))
print("Shortest path:", nx.shortest_path(G, "Airport", "Stadium", weight="weight"))
print("Minutes:", nx.shortest_path_length(G, "Airport", "Stadium", weight="weight"))
print("Hops, ignoring weights:", nx.shortest_path_length(G, "Airport", "Stadium"))
bc = nx.betweenness_centrality(G, weight="weight")
print("Betweenness:", {k: round(v, 3) for k, v in bc.items()})
Degree: {'Airport': 1, 'Central': 3, 'Harbor': 3, 'Museum': 2, 'Stadium': 1}
Shortest path: ['Airport', 'Central', 'Harbor', 'Stadium']
Minutes: 27
Hops, ignoring weights: 3
Betweenness: {'Airport': 0.0, 'Central': 0.5, 'Harbor': 0.5, 'Museum': 0.0, 'Stadium': 0.0}

The fastest route is Airport, Central, Harbor, Stadium: 12 + 6 + 9 = 27 minutes. The other route through Museum takes 30. Note the weight="weight" argument. Without it, NetworkX counts hops, not minutes, which is a common source of wrong answers.

Betweenness centrality measures how often a node sits on the shortest paths between other nodes. Central and Harbor each score 0.5, and every other station scores 0. With five stations, each station sits between six pairs of other stations, and Central and Harbor each lie on the fastest route for three of those six pairs. In plain terms, closing either one would reroute or cut off a large share of trips. That is the “which stations does the network depend on” answer.

Step 4: Directed Graphs

Say the Harbor to Stadium line becomes one-way, from Harbor to Stadium only. In matrix terms, entry (Stadium, Harbor) becomes 0 while (Harbor, Stadium) stays 9. Build a directed graph so the direction is kept:

D_mat = A.copy()
D_mat[4, 2] = 0
D = nx.from_numpy_array(D_mat, create_using=nx.DiGraph, nodelist=stations)
print(D)
print("Stadium -> Airport path exists:", nx.has_path(D, "Stadium", "Airport"))
DiGraph with 5 nodes and 9 edges
Stadium -> Airport path exists: False

The directed graph has 9 edges, one for each nonzero entry. Stadium now has no way out, which has_path confirms. With a DiGraph, row i is always the source and column j the target.

Step 5: Go Back to NumPy

Some work is easier as matrix math. nx.to_numpy_array converts a graph back to an array, with rows in the order you choose. The to_numpy_array reference covers options such as nonedge and how multigraph weights are combined.

back = nx.to_numpy_array(G, nodelist=stations, weight="weight")
print("Round trip equal:", np.array_equal(back, A))

# Graph powers: (A>0)^2 counts 2-step walks
B = (A > 0).astype(int)
print("2-step walks from Airport:", dict(zip(stations, np.linalg.matrix_power(B, 2)[0].tolist())))
Round trip equal: True
2-step walks from Airport: {'Airport': 1, 'Central': 0, 'Harbor': 1, 'Museum': 1, 'Stadium': 0}

The round trip matches the original array. The second line uses a classic property of adjacency matrices: entry (i, j) of B raised to the power k counts the walks of length k from i to j. From Airport, two steps reach Harbor, Museum, or back to Airport through Central. Matrix powers like this are the basis of many spectral graph methods.

Pitfalls to Check

  • Zero-weight edges vanish. A zero is read as “no edge”. If a real connection can have a cost of 0, mark missing edges with np.nan and pass nonedge=np.nan (NetworkX 3.7 or later).
  • The diagonal becomes self-loops. Any nonzero value on the diagonal adds an edge from a node to itself. Set the diagonal to 0 with np.fill_diagonal(A, 0) if that is not what you mean.
  • Similarity versus distance. Shortest path algorithms treat weight as a cost. If your matrix holds similarities (higher means closer), convert them, for example to 1 / similarity, before asking for shortest paths.
  • Large sparse graphs. A dense array of 100,000 nodes would hold 10 billion cells. For large, sparse networks, build the graph from an edge list or a SciPy sparse matrix with nx.from_scipy_sparse_array.

Graphs built this way are also a common input to clustering. If you work with location data, our post on k-means clustering for spatial analysis covers a related approach that groups points by distance rather than by links.

Back to the Five Stations

The array from the opening answered both questions in a few lines. The fastest airport to stadium trip is 27 minutes through Central and Harbor, and those two stations carry the network: each lies on the fastest route for half of the station pairs it could connect. When a line turned one-way, a directed graph showed right away that the stadium could no longer reach the airport. The conversion from NumPy took one call. Getting it right meant choosing node names, direction and what a zero means.

Frequently Asked Questions

What Happened to from_numpy_matrix?

It was removed in NetworkX 3.0, along with to_numpy_matrix, because NumPy’s matrix class is discouraged. Use from_numpy_array and to_numpy_array with regular NumPy arrays instead. The arguments are largely the same.

How Do I Keep My Own Node Labels?

Pass nodelist= to from_numpy_array on NetworkX 3.4 or later. The list must have one label per row, in row order. On older versions, build the graph first and rename the nodes with nx.relabel_nodes.

Can I Convert a pandas DataFrame Instead?

Yes. nx.from_pandas_adjacency reads a square DataFrame and uses its index as node labels. If your data is a table of edges (source, target, weight), use nx.from_pandas_edgelist, which is usually the more natural format for large graphs.

Why Is My Graph Missing Edges?

The most common causes are zeros that were real connections, building an undirected graph from a non-symmetric matrix, and fractional weights that became zero when the array was cast to integers. Print G.number_of_edges() and compare it with the count of nonzero entries in your array.

Disclaimer: The content on this website reflects the views of contributing authors and not necessarily those of Generative AI Lab. This site may contain sponsored content, affiliate links, and material created with generative AI. Thank you for your support.

Generative AI Lab mascot
Generative AI Lab Editorial Team
Articles researched, written and edited by the Generative AI Lab team. About Generative AI Lab

Must read

- Advertisement -spot_img

More articles

- Advertisement -spot_img

Latest articles