Reputation: 237
I'm using NetworkX to create a weighted graph (not a digraph). Each node has a node name and a number of edges that have a weight. The weights are always positive, non-zero integers.
What I'm trying to do is get a list of tuples where each tuple represents a node in the graph (by name) and the weighted degree of the node.
I can do something like this:
the_list = sorted(my_graph.degree_iter(),key=itemgetter(1),reverse=True)
But this doesn't appear to be taking the weighting of each node into account. Each node may have a different weight for every edge (or they may be the same, there's no way to know).
Do I need to write a function to do this manually? I've been coming through the NetworkX docs and am coming up empty on a built-in way to do this (but maybe I'm overlooking it).
If I have to write the function myself, I'm assuming I use the size()
method with the weight
flag set. That seems to only give me the sum of all the weights in the graph though.
Any help is greatly appreciated.
Upvotes: 9
Views: 16676
Reputation: 25289
You can use the Graph.degree() method with the weight= keyword like this:
In [1]: import networkx as nx
In [2]: G = nx.Graph()
In [3]: G.add_edge(1,2,weight=7)
In [4]: G.add_edge(1,3,weight=42)
In [5]: G.degree(weight='weight')
Out[5]: {1: 49, 2: 7, 3: 42}
In [6]: G.degree(weight='weight').items()
Out[6]: [(1, 49), (2, 7), (3, 42)]
Upvotes: 15