3

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

Tim D
  • 111
  • 1
  • 2
  • 7
  • 1
    quick comment - make sure you're aware that the two answers you got make different assumptions about what weights you're after (is it the weight of the edge, or the node weight of the neighbor). – Joel May 03 '18 at 19:01
  • Yep I know. I was looking for edge weight. Sorry for the bad explanation. Thank you however for showing me it also works for nodes :). – Tim D May 04 '18 at 13:25

2 Answers2

3

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

PriyankaP
  • 109
  • 6
1

I'm going to assume that "all the neighbors with a certain weight value" refers to node weights. I'll do the example finding neighbors of weight greater than a particular value.

import networkx as nx
import random

G = nx.Graph()

#now create nodes with random weights.  If this notation is
#unfamiliar, read up on list comprehensions.  They make life much easier.
nodes = [(node, {'weight':random.random()}) for node in range(10)]
G.add_nodes_from(nodes)

#now G has the nodes and they each have a random weight.
G.nodes(data=True)
> [(0, {'weight': 0.42719462610483916}),
 (1, {'weight': 0.13985473528922154}),
 (2, {'weight': 0.06889096983404697}),
 (3, {'weight': 0.10772762947744585}),
 (4, {'weight': 0.24497933676194383}),
 (5, {'weight': 0.18527691296273396}),
 (6, {'weight': 0.16379510964497113}),
 (7, {'weight': 0.5481883941716088}),
 (8, {'weight': 0.3782931298078134}),
 (9, {'weight': 0.5902126428368549})]

#now create edges from 0 to all other nodes
zero_edges = [(0,u) for u in range(1,10)]
G.add_edges_from(zero_edges)

#now find all neighbors of 0 with weight > 0.5
heavy_neighbors = [nbr for nbr in G.neighbors(0) if G.node[nbr]['weight']>0.5]
heavy_neighbors
>[7,9]

If you wanted to, you could also make heavy_neighbors be a generator by replacing the outer [ and ] with ( and ).

Joel
  • 22,598
  • 6
  • 69
  • 93