pythongraphlogicnetworkx

networkx graph get groups of linked/connected values


I've got such data

import networkx as nx

G = nx.Graph()
G.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
G.add_edges_from([(1, 2), (1, 3), (2, 4), (5, 6), (7)])

As you can see 1 is connected with 2 (edge 1, 2) and 1 is connected with 3. This means that 2 is connected with 3 via 2.

So I'd like to get 3 arrays:

First - [1,2,3,4], second - [5,6], because 5 and 6 does not connect with rest values and third array [7]

I expect getting arrays with connected values between each other.


Solution

  • You find to find the connected_components:

    import networkx as nx
    
    G = nx.Graph()
    G.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
    G.add_edges_from([(1, 2), (1, 3), (2, 4), (5, 6), (7)])
    
    out = list(nx.connected_components(G))
    

    And for a DiGraph, nx.weakly_connected_components:

    import networkx as nx
    
    G = nx.DiGraph()
    G.add_nodes_from([1, 2, 3, 4, 5, 6, 7])
    G.add_edges_from([(1, 2), (1, 3), (2, 4), (5, 6), (7)])
    
    out = list(nx.weakly_connected_components(G))
    

    Output:

    [{1, 2, 3, 4}, {5, 6}, {7}]
    

    Graph:

    enter image description here