我使用 networkx.add_edge(),但没有添加边缘?为什么?

I use networkx.add_edge(),but nothing of edges added? why?

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 children

如果 firm1 是 firm2 的 children 则取 1 否则取 0.

但是我使用上面的函数没有添加任何边。

在[177]中:g.edges()

输出[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?

使用了错误的值