Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NetworkX Get Degree of Node with Weights Applied

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.

like image 699
TheOriginalBMan Avatar asked Jan 10 '15 15:01

TheOriginalBMan


People also ask

How do I find the degree of a node in NetworkX?

degree(). The node degree is the number of edges adjacent to the node. The weighted node degree is the sum of the edge weights for edges incident to that node. This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.

How do you find the degree of a node?

where the sum is over all nodes in the network. and the in-degree is the number of incoming edges onto a node kini=∑jaij. The total degree of the node is the sum of its in- and out-degree ktoti=kini+kouti. For this undirected network, the degrees are k1=1, k2=3, k3=1, k4=1, k5=2, k6=5, k7=3, k8=3, k9=2, and k10=1.

How do you find the average degree of a network in NetworkX?

The average degree of an undirected graph is the sum of the degrees of all its nodes divided by the number of nodes in the graph. It is a measure of the connectedness of a graph.


1 Answers

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)]
like image 190
Aric Avatar answered Sep 27 '22 19:09

Aric