Search code examples
pythonnetworkxgraph-theorybipartiteconnected-components

Connected components of bipartite graphs


I'd like to extract connected components (as bipartite graphs) from a bipartite graph using networkx. But connected components in networkx is not for bipartite graphs but general undirected and direct graphs. Is there an example of bipartite graphs? Thanks.


Solution

  • The subgraphs corresponding to connected components of a bipartite graphs (and indeed any graph) themselves carry over all node attributes, so that in particular, you can use those to mark your partitions, as in the docs:

    In [28]: B = nx.Graph()
        ...: B.add_nodes_from([1, 2, 3, 4], bipartite=0)
        ...: B.add_nodes_from(['a', 'b', 'c'], bipartite=1)
        ...: B.add_edges_from([(1, 'a'), (1, 'b'), (2, 'b'), (2, 'a'), (3, 'c'), (4, 'c')])
        ...:
        ...: G = B.subgraph(next(nx.connected_components(B)))
    
    In [30]: G.nodes
    Out[30]: NodeView((1, 2, 'a', 'b'))
    
    In [31]: G.nodes[1]
    Out[31]: {'bipartite': 0}