简体   繁体   English

如何在networkx中使用python随机排列图的节点?

[英]How can I randomly permute the nodes of a graph with python in networkx?

I think this can be done with relabel_nodes, but how can I create a mapping that permutes the nodes?我认为这可以通过 relabel_nodes 来完成,但是如何创建一个置换节点的映射? I want to permute the nodes of a graph while keeping the network structure intact.我想在保持网络结构完整的同时置换图的节点。 Currently I am rebuilding the graph with a shuffled set of nodes which doesn't seem the most efficient way to go about things:目前,我正在使用一组无序的节点重建图形,这似乎不是最有效的处理方式:

import networkx as nx
import random

n=10
nodes=[]
for i in range(0,n):
  nodes.append(i)
G=nx.gnp_random_graph(n,.5)
newG=nx.empty_graph(n)
shufflenodes=nodes
random.shuffle(shufflenodes)
for i in range(0,n-1):
  for j in range(i+1,n):
    if(G.has_edge(i,j)):
      newG.add_edge(shufflenodes[i],shufflenodes[j])

Anyone have any ideas how to speed this up?任何人有任何想法如何加快速度?

What you can do is to build a random mapping and use relabel_nodes .您可以做的是构建一个随机映射并使用relabel_nodes

Code:代码:

# create a random mapping old label -> new label
node_mapping = dict(zip(G.nodes(), sorted(G.nodes(), key=lambda k: random.random())))
# build a new graph
G_new = nx.relabel_nodes(G, node_mapping)

Example:例子:

>>> G.nodes()
NodeView((0, 1, 2, 3, 4))
>>> G.edges()
EdgeView([(0, 1), (0, 2), (0, 3), (1, 2), (3, 4)])
>>> node_mapping
{0: 2, 1: 0, 2: 3, 3: 4, 4: 1}
>>> G_new.nodes()
NodeView((2, 0, 3, 4, 1))
>>> G_new.edges()
EdgeView([(2, 0), (2, 3), (2, 4), (0, 3), (4, 1)])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM