如何从网络图中删除随机数量的节点?

时间:2016-01-20 20:13:04

标签: python networkx

import networkx as nx
import itertools
import numpy as np
import os
import sys
import pylab as pl

g = nx.read_edgelist('/home/suman/Desktop/dataset/Email-Enron.txt',
                     create_using=None, nodetype=int, edgetype=int)

n = nx.number_of_nodes(g)

print n

1 个答案:

答案 0 :(得分:1)

这是一个可能的解决方案,基于一小部分数据:

import networkx as nx
import random

G = nx.Graph()

G.add_edges_from([(1,2),(1,3),(3,4),(4,5)])

ListOfNodes = G.nodes()
NumberofNodes = G.number_of_nodes()

返回G.nodes()

ListOfNodes = [1, 2, 3, 4, 5]

然后根据节点的总数定义要获取的节点样本 您的图表(此处为3,在您的情况下,您可以设置int(NumberofNodes*0.1)的样本:

sample = 3
RandomSample = random.sample(ListOfNodes, sample)

然后您可以使用以下命令从图表中删除示例节点:

G.remove_nodes_from(RandomSample)

回复您获得的G.nodes()

[1, 4, 5]

编辑: RandomSample = random.sample(ListOfNodes, sample)存在问题,因为networkx从1开始节点编号。现在它应该可以直接从节点列表中正确选择节点的随机sample