PyG from_networkx and Node Order: Keeping a Reliable ID Mapping
Yes, torch_geometric.utils.from_networkx preserves node order, in one precise sense: row i of every node tensor belongs to the i-th node of list(G.nodes()). That is the insertion order of the NetworkX graph. The function does not sort the nodes, does not look at integer labels, and does not return the mapping. Edge columns are a different matter: they follow the adjacency structure, not the order in which you added edges.
So the safe habit is one line, executed before you change the graph again:
import networkx as nx
import torch
from torch_geometric.utils import from_networkx
G = nx.Graph()
G.add_edge("carol", "alice")
G.add_edge("bob", "carol")
G.add_node("zed") # no edges
G.add_edge("alice", "bob")
ids = list(G.nodes()) # row i of the tensors is ids[i]
data = from_networkx(G)
index_of = {node: i for i, node in enumerate(ids)}
print(ids) # ['carol', 'alice', 'bob', 'zed']
print(data.num_nodes, data.num_edges) # 4 6
print(data.edge_index.tolist()) # [[0, 0, 1, 1, 2, 2], [1, 2, 0, 2, 0, 1]]
The behaviour below was checked with PyTorch Geometric 2.8.1 and NetworkX 3.7 on CPU. The import path is from torch_geometric.utils import from_networkx.
What the converter actually does
The relevant part of torch_geometric/utils/convert.py in 2.8.1 is short:
G = G.to_directed() if not nx.is_directed(G) else G
mapping = dict(zip(G.nodes(), range(G.number_of_nodes())))
for i, (src, dst) in enumerate(G.edges()):
edge_index[0, i] = mapping[src]
edge_index[1, i] = mapping[dst]
Three consequences follow from these lines:
- Node rows follow
G.nodes(). Node attributes are collected in the same iteration, so features stay aligned with their node. - Undirected graphs become directed, so each undirected edge yields two columns (a self-loop yields one).
- Edge columns follow
G.edges(), which walks node by node through each adjacency dictionary.
Check the whole mapping with assertions, not by eye. This round trip decodes every column back to a pair of original ids:
decoded = {(ids[s], ids[d]) for s, d in data.edge_index.t().tolist()}
expected = {(u, v) for u, v in G.to_directed().edges()}
assert decoded == expected
assert data.num_nodes == len(ids) == len(set(ids))
assert index_of["zed"] == 3 and 3 not in data.edge_index.tolist()[0]
The isolated node zed still gets a row. A model produces an output for it even though no edge mentions it.
The figure shows the same four ids under two indexing rules. Its edge columns are listed in input order, which is useful for following one edge, but it is not the column order that from_networkx produces.
The same ids under first seen order and sorted order
A table mapping the ids carol, alice, bob and zed to indices, and three edges written as index pairs. Choosing sorted order instead of first seen order changes which row each person gets.
| index | original id |
|---|---|
| 0 | carol |
| 1 | alice |
| 2 | bob |
| 3 | zed |
| k | ids | [0] | [1] | edge no. | back |
|---|---|---|---|---|---|
| 0 | carol → alice | 0 | 1 | 1 | carol → alice |
| 1 | bob → carol | 2 | 0 | 2 | bob → carol |
| 2 | alice → bob | 1 | 2 | 3 | alice → bob |
Round trip: 3 of 3 edges decode to their original ids.
Mapping in first-seen order: 4 nodes get indices 0 to 3.
Integer labels are not row numbers
If your nodes are already integers, it is tempting to read label 5 as row 5. That holds only when the nodes were inserted in the order 0, 1, 2, …. Adding edges first usually breaks it:
H = nx.DiGraph([(3, 1), (1, 0), (0, 2)])
print(list(H.nodes())) # [3, 1, 0, 2]
print(from_networkx(H).edge_index.tolist()) # [[0, 1, 2], [1, 2, 3]]
labels = torch.tensor([10, 11, 12, 13]) # labels[k] belongs to NODE k
wrong = labels # silently assumes row == label
right = labels[torch.tensor(list(H.nodes()))]
print(right.tolist()) # [13, 11, 10, 12]
assert not torch.equal(wrong, right)
Nothing raises here. Any array indexed by node label (labels, features, split masks loaded from a file) must be reordered with list(H.nodes()) before you attach it to the Data object.
nx.convert_node_labels_to_integers has the same trap in a less obvious form. Its ordering argument changes which integer each node receives, but not the iteration order of the new graph, and from_networkx looks only at the latter:
K = nx.convert_node_labels_to_integers(G, ordering="sorted", label_attribute="name")
print(list(K.nodes(data="name")))
# [(2, 'carol'), (0, 'alice'), (1, 'bob'), (3, 'zed')]
print(from_networkx(K).name)
# ['carol', 'alice', 'bob', 'zed']
The node now labelled 0 (alice) is in row 1, not row 0. Asking for sorted labels did not sort the rows.
Edge columns follow adjacency, not insertion
For node tensors you only need the node order. For anything stored per edge in a separate array, you also need to know the column order. It groups edges by source node, in node order:
D = nx.DiGraph()
D.add_edge("c", "a")
D.add_edge("b", "c")
D.add_edge("c", "b")
D.add_edge("a", "b")
print(list(D.nodes())) # ['c', 'a', 'b']
print(list(D.edges())) # [('c', 'a'), ('c', 'b'), ('a', 'b'), ('b', 'c')]
The edge added second, b → c, ends up last. Never zip a list of edge values kept in insertion order against edge_index. Put the values on the NetworkX edges instead, so that the converter moves them together.
When the node order changes under your feet
list(G.nodes()) describes one graph object at one moment. Several ordinary operations give a different order for what you may regard as the same graph.
Two graphs that compare equal. nx.utils.graphs_equal compares content, not order:
a = nx.Graph([("u", "v"), ("w", "u")])
b = nx.Graph([("w", "u"), ("u", "v")])
print(nx.utils.graphs_equal(a, b)) # True
print(list(a), list(b)) # ['u', 'v', 'w'] ['w', 'u', 'v']
This is the usual way a pipeline drifts: an edge file is regenerated with its rows in another order, the graph is "the same", and the rows move.
In-place relabelling and re-adding. nx.relabel_nodes(..., copy=True) keeps positions. With copy=False, a renamed node moves to the end, as does a node you remove and add again:
P = nx.path_graph(["a", "b", "c", "d"])
print(list(nx.relabel_nodes(P, {"b": "B"}))) # ['a', 'B', 'c', 'd']
nx.relabel_nodes(P, {"b": "B"}, copy=False)
print(list(P)) # ['a', 'c', 'd', 'B']
Subgraph views. This one varies between runs of the same script. When G.subgraph(keep) keeps fewer than half of the nodes, NetworkX 3.7 iterates over a Python set of the kept ids. Set order for strings depends on hash randomisation, so a new process can number the rows differently. The block below runs the same two lines under three hash seeds:
import os
import subprocess
import sys
program = (
"import networkx as nx\n"
"G = nx.path_graph([f'n{i}' for i in range(12)])\n"
"print(list(G.subgraph(['n7', 'n2', 'n9', 'n4'])))\n"
)
orders = []
for seed in ("0", "1", "3"):
env = dict(os.environ, PYTHONHASHSEED=seed)
run = subprocess.run([sys.executable, "-c", program], env=env,
capture_output=True, text=True, check=True)
orders.append(run.stdout.strip())
print(seed, orders[-1])
assert len(set(orders)) > 1
On CPython 3.13 it printed:
0 ['n7', 'n4', 'n9', 'n2']
1 ['n4', 'n9', 'n7', 'n2']
3 ['n2', 'n9', 'n4', 'n7']
Setting PYTHONHASHSEED hides the symptom for one environment. Choosing the order yourself removes it.
A conversion with an explicit ordering contract
The contract has three parts: the caller can state the node order, edges are added in a canonical order before conversion, and the id list is returned together with the tensors.
def to_data_with_ids(G, order=None):
"""Convert G so that row i is ids[i], independent of how G was built."""
ids = sorted(G.nodes()) if order is None else list(order)
if len(ids) != G.number_of_nodes() or set(ids) != set(G.nodes()):
raise ValueError("order must list every node of G exactly once")
row = {node: i for i, node in enumerate(ids)}
def edge_key(edge):
a, b = row[edge[0]], row[edge[1]]
return (a, b) if G.is_directed() else (min(a, b), max(a, b))
H = type(G)()
H.graph.update(G.graph)
H.add_nodes_from((n, G.nodes[n]) for n in ids)
H.add_edges_from(sorted(G.edges(data=True), key=edge_key))
return from_networkx(H), ids
da, ids_a = to_data_with_ids(a)
db, ids_b = to_data_with_ids(b)
assert ids_a == ids_b == ["u", "v", "w"]
assert torch.equal(da.edge_index, db.edge_index)
Because the edges are inserted into H in row order, the columns come out sorted by source and then target, and every edge attribute travels with its edge. Sorting in NetworkX is deliberate: reordering afterwards with Data.sort relies on PyG guessing which attributes are per edge, and that guess can fail when a graph has as many nodes as edges (attributes whose names do not contain "edge" are then treated as node attributes). The default sorted(G.nodes()) needs ids that can be compared with each other. For a mix of strings and integers, pass an explicit order, for example the row order of the table that holds your node features. That is usually the best choice anyway, because features and labels are then aligned without any reindexing. For MultiGraph inputs, parallel edges between the same pair are not ordered by their attribute values, so sort the source rows before building the graph if that matters.
Testing the contract
A unit test for this takes a shuffled copy of the graph and expects identical tensors. Use a seeded generator so that a failure can be reproduced:
import random
def rebuild_shuffled(G, seed):
rng = random.Random(seed)
nodes = list(G.nodes())
edges = list(G.edges(data=True))
rng.shuffle(nodes)
rng.shuffle(edges)
H = type(G)()
H.add_nodes_from(nodes)
H.add_edges_from(edges)
return H
reference, ref_ids = to_data_with_ids(G)
for seed in range(20):
shuffled, shuffled_ids = to_data_with_ids(rebuild_shuffled(G, seed))
assert shuffled_ids == ref_ids
assert torch.equal(shuffled.edge_index, reference.edge_index)
print("20 shuffled builds give the same tensors")
Getting predictions back to the original ids
Keep ids next to the model output and decode by position:
ids = ref_ids
scores = torch.tensor([[0.2, 0.8], [0.9, 0.1], [0.4, 0.6], [0.7, 0.3]]) # stand-in output [N, Q]
by_id = {ids[row]: int(cls) for row, cls in enumerate(scores.argmax(dim=1))}
print(by_id) # {'alice': 1, 'bob': 0, 'carol': 1, 'zed': 0}
Save the list with the model checkpoint, for example as JSON. A weight file trained on one row order is not meaningful for another if the model has per-node parameters, and predictions cannot be decoded without the list.
You can also store the ids on the object, as in data.node_name = ids. In 2.8.1, Data.subgraph did subset such a list together with the node tensors in our test. For mini-batch loaders that return a global index per row, such as n_id in PyG's NeighborLoader, decode with ids[global_row].
Other converters number nodes differently
Do not carry a mapping from one library to another without checking it.
| Converter | Row i is |
Checked with |
|---|---|---|
PyG from_networkx |
i-th node of list(G.nodes()) |
2.8.1 |
TGraphX Graph.from_networkx |
i-th node of list(G.nodes()) |
1.5.1 |
DGL dgl.from_networkx |
node whose label is i-th in sorted order |
2.1.0, and the 2.4.0 source |
DGL calls nx.convert_node_labels_to_integers(..., ordering="sorted") and then numbers by the assigned integer. For the graph c, a, b with one edge c → a, DGL stores the edge as 2 → 0, while PyG stores it as 0 → 1. DGL also fails on labels that cannot be compared with each other. For choosing between these libraries see the tool selection matrix and the comparison hub.
TGraphX follows the PyG rule for node rows, with two differences that matter: it copies at most one node attribute, and its handling of undirected self-loops is not the same. TGraphX vs NetworkX shows how the two libraries are used together, and the getting-started FAQ has the two-line version of the conversion.
Checklist
- Capture
ids = list(G.nodes())immediately before converting, or pass an explicit order. - Never assume that integer labels equal row indices.
- Attach per-edge values to NetworkX edges, not to a parallel list.
- Avoid converting subgraph views directly when reproducibility matters.
- Assert the decoded edge set, and save the id list with the model.
References
- PyG team. torch_geometric.utils documentation (
from_networkx,to_networkx). - NetworkX developers. convert_node_labels_to_integers.
- DGL team. dgl/convert.py at v2.4.0, source of
from_networkx. - Python documentation. Command line and environment (
PYTHONHASHSEED). - Matthias Fey and Jan E. Lenssen. Fast Graph Representation Learning with PyTorch Geometric. 2019.