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()