import networkx as net
def get_Children(g, df):
for i in range(0, (df.iloc[:,0].size)-1):
f1 = df.iloc[i]['firm1']
f2 = df.iloc[i]['firm2']
if f1 != f2:
if df.iloc[i]['children'] == 1.0:
g.add_edge(f1, f2)
else: continue
return g
g = net.Graph()
g.add_nodes_from(index)
get_Children(g, df)
像这样的数据:
坚定1公司2儿童
如果firm1是firm2的孩子,那么得到1否则为0。
但我使用上面的功能添加任何边缘。
在[177]:g.edges()
Out [177]:EdgeView([])
我试图在这里重现你的代码,我似乎已经能够使用add_edge()
生成边缘,主要使用你提供的代码:
import pandas as pd
import networkx as nx
df = pd.DataFrame({'firm1':[1,1,1,2,2,2,3,3,3,4,4,4],
'firm2':[2,3,4,3,1,4,1,2,4,1,2,3],
'children':[0,1,0,1,0,1,0,0,0,0,0,0]})
这给出了您提供的DataFrame:
children firm1 firm2
0 0 1 2
1 1 1 3
2 0 1 4
3 1 2 3
4 0 2 1
5 1 2 4
6 0 3 1
7 0 3 2
8 0 3 4
9 0 4 1
10 0 4 2
11 0 4 3
我复制了你的其余代码,我唯一改变的就是用index
替换[1,2,3,4]
(还有用net
替换nx
,这是NetworkX包的惯例:
def get_Children(g, df):
for i in range(0, (df.iloc[:,0].size)-1):
f1 = df.iloc[i]['firm1']
f2 = df.iloc[i]['firm2']
if f1 != f2:
if df.iloc[i]['children'] == 1.0:
g.add_edge(f1, f2)
else: continue
return g
g = nx.Graph()
g.add_nodes_from([1,2,3,4])
get_Children(g, df)
g.edges()
g.edges()
导致:
EdgeView([(1, 3), (2, 3), (2, 4)])
我正在使用Python 3来重现这一点。也许你使用的index
值不正确?