Search code examples
pythonnetworkxedges

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)

data like this:

firm1 firm2 children

  • firm1 firm2 children
  • 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

if firm1 is the children of firm2 then get 1 otherwise 0.

but i use the function above add nothing of edges.

In [177]: g.edges()

Out[177]: EdgeView([])


Solution

  • I have tried to reproduce your code here and I seem to have been able to produce edges with add_edge() using mostly the code you provided:

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

    This gives the DataFrame you provided:

        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
    

    I replicated the rest of your code, and the only thing I changed was replacing index with [1,2,3,4] (and also net with nx, the convention for the NetworkX package:

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

    The g.edges() results in:

    EdgeView([(1, 3), (2, 3), (2, 4)])
    

    I'm using Python 3 to reproduce this. Perhaps you were using an incorrect value for index?