简体   繁体   English

使用networkx添加边缘

[英]Add edges using networkx

Are there any easy method to add a large number of edges together in networkx 是否有任何简单的方法可以在networkx中将大量边缘添加在一起

I want to add edges from a list. 我想从列表中添加边。

Assuming that by "add a large number of edges together" you mean "add them to a graph", from help(networkx.Graph) : 假设通过“将大量边​​加在一起”,您的意思是从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)])

And so: 所以:

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

I would definitely recommend getting in the habit of reading the interactive documentation. 我绝对建议养成阅读交互式文档的习惯。 I was using IPython , and so all I had to do to quickly skim the available methods was make a graph g , and then type g.[TAB] . 我正在使用IPython ,因此,为了快速浏览可用方法,我要做的就是绘制图形g ,然后键入g.[TAB] This brought up a list, and g.add_edges_from was #3. 这显示了一个列表, g.add_edges_from是#3。

OTOH, if you simply want to add two lists of edges together, you can do that too: 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)])

Often graph data is stored in a file, which makes it easy to read with Pandas dataframe. 图形数据通常存储在文件中,这使得使用Pandas数据框易于读取。 For example, consider constructing a graph for a seventh grader network . 例如,考虑为七年级学生网络构建图。 We can initialize our graph as follows: 我们可以如下初始化图形:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM