Search code examples
pythongraphnetworkx

Networkx, get all in_edges of a node


I use in_edges method as described in doc to get all incoming edges to a node G[myIndex] in a DiGraph, butfor u, v, data in G.in_edges(G[maxIndex], data=True): actualy gives me all out_edges. Not my desired output.

When I try G.out_edges it gives me all edges coming from all out_edges(like one step further from the desired output). Is there something I'm missing in passing my desired node to the nbunch parameter? It seems like a bug to me, but in that case it would be easy to google it, so I think I'm wrong.

screen In the image, it can be seen at the right side, that in_edges of edge 0 is giving out edges as seen at left side... it can be also seen, that the in_degree is 3.


Solution

  • I think you're misunderstanding what G[maxIndex] does. It will actually give you the out-edges of node maxIndex and then getting the in-edges from that bunch of nodes.

    If you simply want the in-edges of a given node you can do G.in_edges(maxIndex, data=True). Like so:

    G = nx.DiGraph()
    G.add_weighted_edges_from([(2, 1, 3.0), (3,1, 5.0), (4, 1, -1.0), (4, 2, 8.0)])
    maxIndex = 1  # Here
    for u, v, data in G.in_edges(maxIndex, data=True):
        print(u,v,data)
    

    Output:

    2 1 {'weight': 3.0}
    3 1 {'weight': 5.0}
    4 1 {'weight': -1.0}