Search code examples
python-2.7networkxneighbours

Python - Networkx: Neighbours with certain weight


This question setting is python 2.7 using the package networkx: https://networkx.github.io/documentation/stable/reference/classes/generated/networkx.Graph.neighbors.html

I'm looking for a way to use the function "networkx.Graph.neighbors" which returns me all the neighbors with a certain weight value (or higher/lower than a certain value).

Any suggestions how I could make this possible?

Thanks in advance :). Tim


Solution

  • Lets assume that you want to filter 'c' node neighbors according to the weight.Creating the following graph:

        G = nx.Graph()
        G.add_edge('a', 'b', weight=0.6)
        G.add_edge('a', 'c', weight=0.2)
        G.add_edge('c', 'd', weight=0.1)
        G.add_edge('c', 'e', weight=0.7)
        G.add_edge('c', 'f', weight=0.9)
        G.add_edge('a', 'd', weight=0.3)
    
        list_neighbors=G.neighbors('c')
        for i in list_neighbors:
            if G.edges[('c',i)]['weight']>0.5:
                print (G.edges[('c',i)])
    

    Gives: {'weight': 0.7} {'weight': 0.9} Hope this answers your question. Refer to the link if you need more info on how to work with weights. https://networkx.github.io/documentation/stable/auto_examples/drawing/plot_weighted_graph.html