partition graph into sungraphs based on node's attribute NetworkX

前端 未结 1 526
面向向阳花
面向向阳花 2021-01-03 15:59

I\'m using Networkx to compute some measures of a graph such as diameter, clustering coefficient, etc. It\'s straight forward how to do this for graph as a whole. What I\'m

相关标签:
1条回答
  • 2021-01-03 16:16

    Use Graph.subgraph(nodes)

    NetworkX 2.x+:

    Demo

    import networkx as nx
    
    G = nx.Graph()
    
    G.add_nodes_from([1, 2, 3], color="red")
    G.add_nodes_from([4, 5, 6])
    G.nodes  # NodeView((1, 2, 3, 4, 5, 6))
    
    # create generator
    nodes = (
        node
        for node, data
        in G.nodes(data=True)
        if data.get("color") == "red"
    )
    subgraph = G.subgraph(nodes)
    subgraph.nodes  # NodeView((1, 2, 3))
    

    older NetworkX's

    Iterate over (Graph.iter_nodes()) and filter the nodes based on your criteria. Pass that list to Graph.subgraph() and it'll return a copy of those nodes and their internal edges.

    For example:

    G = nx.Graph()
    # ... build or do whatever to the graph
    nodes = (n for n, d in G.nodes_iter(data=True)) if d.get('color') == 'red')
    subgraph = G.subgraph(nodes)
    
    0 讨论(0)
提交回复
热议问题