atomh33ls - 2 years ago 160

Python Question

Say I have two networkx graphs,

`G`

`H`

`G=nx.Graph()`

fromnodes=[0,1,1,1,1,1,2]

tonodes=[1,2,3,4,5,6,7]

for x,y in zip(fromnodes,tonodes):

G.add_edge(x,y)

H=nx.Graph()

fromnodes=range(2,8)

tonodes=range(8,14)

for x,y in zip(fromnodes,tonodes):

H.add_edge(x,y)

I'd like to preserve the node names (note the common nodes, 2 to 7). When I used

`nx.disjoint_union(G,H)`

`>>> G.nodes()`

[0, 1, 2, 3, 4, 5, 6, 7]

>>> H.nodes()

[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

>>> Un= nx.disjoint_union(G,H)

>>> Un.nodes()

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

#

The

`H`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

The function you're looking for is compose.

```
import networkx as nx
G=nx.Graph()
G.add_edge(1,2)
H=nx.Graph()
H.add_edge(1,3)
F = nx.compose(G,H)
F.edges()
> [(1, 2), (1, 3)]
```

There are also other options to do the symmetric difference, intersection, ...

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**