使用networkx添加边缘

时间:2012-08-27 12:15:16

标签: python networkx

是否有任何简单的方法可以在networkx中添加大量边缘

我想从列表中添加边缘。

2 个答案:

答案 0 :(得分:3)

假设通过“将大量边​​缘添加到一起”,您的意思是“将它们添加到图表中”,来自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)])

答案 1 :(得分:1)

图表数据通常存储在一个文件中,这使得使用Pandas数据帧轻松读取。例如,考虑为seventh grader network构建图表。我们可以按如下方式初始化图表:

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']