读取CSV边集,并用Networkx找出最大连通子图并输出其对应及属性

NetworkX系列教程(7)-对graph进行分析 - 好奇不止,探索不息 - 博客园

复杂网络分析——networkx的使用_小乖多想c的博客-CSDN博客

主要是这句

largest_components=max(nx.connected_components(Gmax),key=len) 
#输出的是一个点的集合[(2,3,4)]

 可以利用如下语句输出点和边

   for c in nx.connected_components(Gmax):
            if i==0:        
                g = Gmax.subgraph(c)
                #print(g)
                g_edge = g.edges()#边
                g_node=g.nodes()#点

也可以用下面的筛选法(整体代码) 


import matplotlib.pyplot as plt

import networkx as nx

def findmaxG(in_path1=None, out_path1=None,in_path2=None, out_path2=None):
    Gatt={}
    graphs = pd.read_csv(in_path1, sep=' ', header=None)
    graphs.columns = ["layerID", "n1", "n2", "weight"]
    f2 = open(in_path2, 'r')
    attdic = eval(f2.read())
    f1 = open(out_path1, 'w')
    for layerID, graph in graphs.groupby(['layerID']):
        print(layerID)
        Gmax = nx.Graph()
        graphlist=graph.values.tolist()
        #print(graphlist)
        edge12 = graph[['n1', 'n2']]
        edge21 = graph[['n2', 'n1']]
        
        edge12list=edge12.values.tolist()
        edge21list=edge21.values.tolist()
        print("去重前的边集大小:"+str(len(edge12list)))
        for e12 in edge12list:
            if e12 in edge21list:
                edge12list.remove(e12)
                #print(e12)
        print("去重后的边集大小:"+str(len(edge12list)))
        Gmax.add_edges_from(edge12list)
        largest_components=max(nx.connected_components(Gmax),key=len)  
        print("最大连通子图节点规模:"+str(len(largest_components)))
        layatt=attdic[layerID]
        layGatt={}
        for node in largest_components:
            if node in layatt:
                layGatt[node]=layatt[node]
        Gatt[layerID]=layGatt
        #print(len(largest_components))
        for a in graphlist:
            if a[1] in largest_components or a[2] in largest_components and a[1]!=a[2] :
                if a[1] not in layatt:
                    layGatt[a[1]]=layatt[a[1]]
                if a[2] not in layatt:
                    layGatt[a[2]]=layatt[a[2]]
                edges = str(a).replace('[', '').replace(']', '')
                edges = edges.replace("'", '').replace(",", '') + '\n'
                f1.write(edges)
        Gatt[layerID]=layGatt
    f1.close()
    f2.close()
    file1 = open(out_path2, 'w')
    file1.write(str(Gatt))
    file1.close()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值