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

问题描述 投票:0回答:1

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儿童

  • 坚定1公司2儿童
  • 1 2 0
  • 1 3 1
  • 1 4 0
  • 2 3 1
  • 2 1 0
  • 2 4 1
  • 3 1 0
  • 3 2 0
  • 3 4 0
  • 4 1 0
  • 4 2 0
  • 4 3 0

如果firm1是firm2的孩子,那么得到1否则为0。

但我使用上面的功能添加任何边缘。

在[177]:g.edges()

Out [177]:EdgeView([])

python networkx edges
1个回答
0
投票

我试图在这里重现你的代码,我似乎已经能够使用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值不正确?

© www.soinside.com 2019 - 2024. All rights reserved.