[英]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()
:我可以使用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
.如果你有足够的可用内存,您可以先创建DiGraph
的所有边,然后删除所有,但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.或者,您可以遍历dfs_edges
并检索边信息以将边和标签添加到有向图。
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'})]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.