简体   繁体   中英

Creating a directed graph from an undirected graph with dfs_tree, but keep attributes

I want to force an undirected graph to a directed graph using a specific node as the root. I can do this using dfs_tree() :

G = nx.Graph([(0, 1, {"color": "red"}), (1, 2, {"color": "blue"}), (3, 2, {"color": "green"})])
DG = nx.dfs_tree(G, 0)

But the problem is that the attributes are lost in the process:

DG.edges(data=True)

OutEdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {})])

Is there a different way to do this, where you don't lose the attributes? Or do I have to map them back manually?

If you have enough memory available, you can first create the DiGraph with all edges and then remove all, but the dfs_edges . This will preserve all attribute information. Alternatively, you could iterate over dfs_edges and retrieve the edge information to add the edge and the label to the directed graph.

import networkx as nx

G = nx.Graph([(0, 1, {"color": "red"}), (1, 2, {"color": "blue"}), (3, 2, {"color": "green"})])
DG = nx.DiGraph(G)

DG.remove_edges_from(DG.edges - nx.dfs_edges(G, 0))

print(DG.edges(data=True))
# [(0, 1, {'color': 'red'}), (1, 2, {'color': 'blue'}), (2, 3, {'color': 'green'})]

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