python - 如何在 Networkx 中将两个 egdes 和节点合并为一个具有共同起始节点的节点?
问题描述
我是 networkx 的新手,我正在向 Stackeroverflow 社区寻求帮助。
我正在尝试组合具有共同起始节点的节点和边,如下图所示。箭头显示预期结果。
nodes_to_combine = [n for n in graph.nodes if len(list(graph.neighbors(n))) == 2]
for node in nodes_to_combine:
graph.add_edge(*graph.neighbors(node))
nx.draw(graph, with_labels=True)
谁能帮我弄清楚这个?
解决方案
NetworkX 没有合并图中节点的功能,因此应该手动实现。这是没有属性合并的示例(它可以有自己的逻辑):
def merge(G, n1, n2):
# Get all predecessors and successors of two nodes
pre = set(G.predecessors(n1)) | set(G.predecessors(n2))
suc = set(G.successors(n1)) | set(G.successors(n2))
# Create the new node with combined name
name = str(n1) + '/' + str(n2)
# Add predecessors and successors edges
# We have DiGraph so there should be one edge per nodes pair
G.add_edges_from([(p, name) for p in pre])
G.add_edges_from([(name, s) for s in suc])
# Remove old nodes
G.remove_nodes_from([n1, n2])
下面是它的工作原理:
import networkx as nx
G = nx.DiGraph()
G.add_edges_from([
('0','20'),
('10','20'),
('10','30'),
('20','40'),
('30','50'),
])
nx.draw(
G,
pos=nx.nx_agraph.graphviz_layout(G, prog='dot'),
node_color='#FF0000',
with_labels=True
)
merge(G, '20', '30')
nx.draw(
G,
pos=nx.nx_agraph.graphviz_layout(G, prog='dot'),
node_color='#FF0000',
with_labels=True
)
推荐阅读
- r - 我怎样才能将这些数据点清楚地添加到图表中,而不会让它们看起来像它们那样?
- javascript - javascript过滤多维数组
- javascript - 如何避免在服务工作者推送事件中显示通知
- kubernetes - 在具有私有 GKE 集群的 Terraform 上使用 Kubernetes 提供程序
- php - Wordpress 密码重置页面重定向到主题的密码重置页面
- python - 如何仅在 CPU 上运行 tflite
- python - 在我当前的项目中实施recycleview
- c - 旋转 90 度统一
- c++ - 循环优化
- python-3.x - 缺少参数/在 macOS Big Sur 上打开 GUI 程序时出现问题