简体   繁体   中英

Aggregating nodes in networkx

How can I efficiently aggregate nodes and either obtain weighted links or a MultiGraph? By aggregate I mean reducing the number of nodes via a mapping dict in a relabelling process:

import networkx as nx

G = nx.path_graph(5)
mapping_dict = {0: 'A', 1: 'B', 2: 'C', 3: 'A', 4: 'B', 5: 'C'}
H = nx.relabel_nodes(G, mapping_dict)
for edge in H.edges(data=True):
     print edge
#('A', 'C', {})
#('A', 'B', {})
#('C', 'B', {})

However I want H to either have a link of weight 2 between A and C (and A and B and B and C ) or two parallel edges. Is there a way to do so?

You could create a new mutigraph (or graph).

import networkx as nx
G = nx.path_graph(5)
mapping_dict = {0: 'A', 1: 'B', 2: 'C', 3: 'A', 4: 'B', 5: 'C'}
H = nx.MultiGraph()
for (u,v) in G.edges():
    H.add_edge(mapping_dict[u],mapping_dict[v])
for edge in H.edges():
     print edge
#('A', 'C')
#('A', 'B')
#('A', 'B')
#('C', 'B')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM