python - 如何将一个图的边权重添加到 NetworkX 中不同图中的匹配边?
问题描述
我在networkx中有两个不同的图,一个图有边的总集合。另一个图是总边的子集。我将如何从边图的总集合中获取权重并将它们添加到新图中的匹配边?
#total edge collection
G.edges(data = True)
OutEdgeDataView([(1, 2, {'weight': 10}), (2, 3, {'weight': 0}), (2, 5, {'weight': 0}), (2, 6, {'weight': 0}),
(2, 1, {'weight': 0}), (3, 4, {'weight': 10}), (3, 7, {'weight': 0}), (3, 8, {'weight': 0}), (3, 2, {'weight': 0}), (4, 3, {'weight': 0}), (5, 2, {'weight': 0}), (6, 2, {'weight': 0}),
(7, 3, {'weight': 0}), (8, 3, {'weight': 0})])
T = nx.Graph()
T.add_edges_from([(1, 2), (2, 3), (2, 5), (2, 6), (3, 8), (3, 4), (3, 7)])
T.edges(data = True)
EdgeDataView([(1, 2, {}), (2, 3, {}), (2, 5, {}), (2, 6, {}), (3, 8, {}), (3, 4, {}), (3, 7, {})])
我希望 T EdgeDataView 看起来像
EdgeDataView([(1, 2, {'weight':10}), (2, 3, {'weight': 0}), (2, 5, {'weight': 0}), (2, 6, {'weight': 0}),
(3, 8, {'weight': 0}), (3, 4, {'weight': 10}), (3, 7, {'weight': 0})])
任何想法,将不胜感激,
解决方案
你可以试试networkxGraph.edge_subgraph
功能。
以你为例。
首先创建图表:
G = nx.DiGraph()
G.add_edges_from([(1, 2, {'weight': 10}), (2, 3, {'weight': 0}), (2, 5, {'weight': 0}), (2, 6, {'weight': 0}),
(2, 1, {'weight': 0}), (3, 4, {'weight': 10}), (3, 7, {'weight': 0}), (3, 8, {'weight': 0}), (3, 2, {'weight': 0}), (4, 3, {'weight': 0}), (5, 2, {'weight': 0}), (6, 2, {'weight': 0}),
(7, 3, {'weight': 0}), (8, 3, {'weight': 0})])
接下来,选择您假装添加到新图中的节点:
edge_set = [(1, 2), (2, 3), (2, 5), (2, 6), (3, 8), (3, 4), (3, 7)]
然后,将边从一个图形提取到另一个图形:
Di_T = G.edge_subgraph(edge_set)
请注意,因为G
是定向的T
也将是定向的,所以:
T = Di_T.to_undirected() # see NOTE in the end
结果
>>> T.edges(data = True)
EdgeDataView([ (1, 2, {'weight': 10}),
(2, 3, {'weight': 0}),
(2, 5, {'weight': 0}),
(2, 6, {'weight': 0}),
(3, 4, {'weight': 10}),
(3, 7, {'weight': 0}),
(3, 8, {'weight': 0})])
完整代码:
# example graph
G = nx.DiGraph()
G.add_edges_from([(1, 2, {'weight': 10}), (2, 3, {'weight': 0}), (2, 5, {'weight': 0}), (2, 6, {'weight': 0}), (2, 1, {'weight': 0}), (3, 4, {'weight': 10}), (3, 7, {'weight': 0}), (3, 8, {'weight': 0}), (3, 2, {'weight': 0}), (4, 3, {'weight': 0}), (5, 2, {'weight': 0}), (6, 2, {'weight': 0}), (7, 3, {'weight': 0}), (8, 3, {'weight': 0})])
# example edge set
edge_set = [(1, 2), (2, 3), (2, 5), (2, 6), (3, 8), (3, 4), (3, 7)]
# solution
T = G.edge_subgraph(edge_set).to_undirected()
T.edges(data = True)
笔记:
通常由G.edge_subgraph(edge_set)
(使用.copy
)制作副本,以获得图形的新副本,而不是原始图形的引用(请参阅文档中的注释)。
但是,.to_undirected
已经制作了图形的深层副本,因此无需.copy
检查G.edge_subgraph
和
.to_undirected
文档以获取更多信息
推荐阅读
- mysql - NodeJS、MySQL - 高级查询
- c - 我怎样才能使用递归公式来获得权力而不给我分段错误?
- javascript - 如何让一个类返回一个值?
- swiftui - 对数组对象的更改未保存到主 ObservableObject
- javascript - 调试高达 809 的基本转换计算器
- html - 如何使用 jinja 在 html 标签中使用变量?
- winappdriver - 如何将 WinAppDriver 切换到另一个版本
- python - 带有逗号的嵌套数组的数据框到json
- pandas - 尝试将 Int 转换为 Categorical 时无法弄清楚语法错误是什么
- sql - 使用多个 where 条件运行特定条件的问题