0

有什么简单的方法可以在networkx中将大量边添加在一起

我想从列表中添加边。

4

2 回答 2

2

假设通过“将大量边​​添加在一起”您的意思是“将它们添加到图形中”,来自help(networkx.Graph)

 |  **Edges:**
 |  
 |  G can also be grown by adding edges.
 |  
 |  Add one edge,
 |  
 |  >>> G.add_edge(1, 2)
 |  
 |  a list of edges,
 |  
 |  >>> G.add_edges_from([(1,2),(1,3)])

所以:

>>> import networkx as nx
>>> g = nx.Graph()
>>> g.add_edges_from([(0,4),(1,2),(2,3)])
>>> g
<networkx.classes.graph.Graph object at 0x1004b58d0>
>>> g.edges()
[(0, 4), (1, 2), (2, 3)]

我肯定会建议养成阅读交互式文档的习惯。我正在使用IPython,所以为了快速浏览可用的方法,我所要做的就是制作一个图表g,然后输入g.[TAB]. 这带来了一个列表,并且g.add_edges_from是#3。

OTOH,如果您只是想将两个边列表添加在一起,您也可以这样做:

>>> g0.edges() + g1.edges()
[(1, 2), (2, 3), (3, 4), (1, 2), (2, 3), (3, 4), (5, 6)]
>>> set(g0.edges() + g1.edges())
set([(1, 2), (3, 4), (5, 6), (2, 3)])
于 2012-08-27T12:29:31.050 回答
1

图形数据通常存储在一个文件中,这使得使用 Pandas 数据框易于阅读。例如,考虑为一个七年级学生网络构建一个图。我们可以如下初始化我们的图:

import pandas as pd
import networkx as nx

#read the edge list
edges = pd.read_csv('./data/moreno_seventh/out.moreno_seventh_seventh', skiprows=2, sep = " ", header=None)
edges.columns = ['student1', 'student2', 'count']

#read node metadata
meta =pd.read_csv('./data/moreno_seventh/ent.moreno_seventh_seventh.student.gender', header=None)
meta.index += 1
meta.columns = ['gender']

#construct the graph
G = nx.DiGraph()
for row in edges.iterrows():
    G.add_edge(row[1]['student1'], row[1]['student2'], count=row[1]['count'])

#add meta data
for i in G.nodes():
    G.node[i]['gender'] = meta.ix[i]['gender']
于 2016-12-26T20:38:28.883 回答