I would like to remove a node from a DiGraph in networkx in such a way that all child nodes are preserved and their edges are remapped (or old edges deleted + new created) to the parent of their parent node. The node will be removed based on the node attributes (such as what group it belongs to).
For instance, I wish to programmatically remove nodes which have attribute Group B and remap all immediate child nodes to the original parent (in the case of multiple grandparents, I want to map to all of them).
I can think of a crude approach by iterating over the DiGraph, looking at its immediate successors and predecessors, creating relationships between them and then removing the node, but is there perhaps any more elegant way?
for node in DiG.nodes(data=True):
if node[1].get('node_group') == "Group B":
pre = DiG.predecessors(node[0])
suc = DiG.successors(node[0])
for p in pre:
for s in suc:
DiG.add_edge(s, p)
DiG.remove_node(node[0])


