【问题标题】:In networkx python, how to connect a new bunch of nodes and edges to each node in a graph?在networkx python中,如何将一组新的节点和边连接到图中的每个节点?
【发布时间】:2019-11-22 08:46:49
【问题描述】:

目前我创建了一个图表如下:

import networkx as nx
edges = []
for i in range (10):
    edges.append((i,i+1))
edges += [(10,0), (1,10), (2,8), (3,7), (4,6), (4,10), (5,10)]
# create the graph
G = nx.Graph()
G.add_nodes_from([i for i in range (11)])
G.add_edges_from(edges)

现在我需要根据 ????=3 的幂律分布将随机数量的新节点连接到上述核心网络的每个节点。 所以我得到了一个具有幂律分布的新图(例如:15 个节点):

s1 = nx.utils.powerlaw_sequence(15, 3) #15 nodes, power-law exponent 3
G1 = nx.expected_degree_graph(s1, selfloops=False)

现在如何将这个新图表连接到我之前网络中的某个节点?尝试过add_nodes_from,但它们似乎覆盖了以前的节点,这很奇怪;而且我无法确保它们已连接到某个节点。或者有什么直接的方法可以做到这一点?感谢您帮助我!

【问题讨论】:

  • 您能提供预期的输出吗?我知道这是随机的,但请举个例子:)
  • 新节点需要新的数字/值——如果你再次添加[i for i in range(11)],那么它会替换它们。如果您添加 [i for i in range(11, 13)],那么它将添加新节点 - 11,12。也许创建具有唯一值的节点 - 即。 (uniq_number, value)

标签: python graph networkx power-law


【解决方案1】:

问题是由于nx.expected_degree_graph 创建了一个图,其节点的标签为0 ... 14。如果您尝试加入GG1,则具有相同名称的节点将被合并。

您需要G1 才能拥有具有唯一标签的节点。您可以使用relabel_nodes 函数实现这样的结果:

relabel_dict = {node: node+len(G.nodes) for node in G1.nodes}
G1 = nx.relabel_nodes(G1, relabel_dict)

现在您可以使用compose 函数安全地加入GG1

new_G = nx.compose(G, G1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多