Search code examples
pythongraphnetworkx

Difference between two NetworkX graphs with different node sets


I want the difference G1-G2 giving an output of edges which exist in G1, but not in G2. The differencefunction in NetworkX allows this difference only when G1 and G2 have same node sets.

My example: G1.edges=EdgeView([(0, 1), (1, 2), (1, 3), (1, 18))

G2.edges=EdgeView([(0, 1), (1, 2), (1, 3), (2, 22)])

Desired output is (1,18)


Solution

  • The EdgeView class defines set operations on edges.
    Thus, you may simply use:

    G1.edges() - G2.edges()
    

    Example:

    >>> G2.edges()
    EdgeView([(0, 1), (1, 2), (1, 3), (2, 22)])
    >>> G1.edges()
    EdgeView([(0, 1), (1, 2), (1, 3), (1, 18)])
    >>> G1.edges() - G2.edges()
    {(1, 18)}