Skip to content

Instantly share code, notes, and snippets.

@Zulko
Last active June 9, 2023 03:23
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save Zulko/7629206 to your computer and use it in GitHub Desktop.
Save Zulko/7629206 to your computer and use it in GitHub Desktop.
This is a function to merge several nodes into one in a Networkx graph
# This is a function to merge several nodes into one in a Networkx graph
def merge_nodes(G,nodes, new_node, attr_dict=None, **attr):
"""
Merges the selected `nodes` of the graph G into one `new_node`,
meaning that all the edges that pointed to or from one of these
`nodes` will point to or from the `new_node`.
attr_dict and **attr are defined as in `G.add_node`.
"""
G.add_node(new_node, attr_dict, **attr) # Add the 'merged' node
for n1,n2,data in G.edges(data=True):
# For all edges related to one of the nodes to merge,
# make an edge going to or coming from the `new gene`.
if n1 in nodes:
G.add_edge(new_node,n2,data)
elif n2 in nodes:
G.add_edge(n1,new_node,data)
for n in nodes: # remove the merged nodes
G.remove_node(n)
@lauraadam
Copy link

Hi, thanks for sharing this function.

FYI -- I noticed a problem if new_node is in nodes: all new_node related edges get deleted at the end. If you always check if the 'current working node' is not new_node it seems to fix it.

Cheers!

@bilalzahid
Copy link

Hi, Nice function.
But if the graph is a weighted graph then u should also add one more line to your function that new_node.weight = nodes.weight (nodes sent for merging)

@bilalzahid
Copy link

There is an issue with this code. For example if we merge two nodes and both have a connection with same node then we have to add the edge weights of both connections when we make new edge.

@mlyzhong
Copy link

@bilalzahid make a pull request!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment