0

I am looking for a way to find the biggest 5 weighted edges in a node. Is there a way to specify that I want exactly the biggest 5 edges without a specific threshold value(a.k.a universal for any weighted graph)?

geralt
  • 5
  • 1
  • I think you are looking for it https://stackoverflow.com/questions/52440518/finding-maximum-weighted-edge-in-a-networkx-graph-in-python – NoobCoder Jan 04 '21 at 17:40
  • Hello, yes I saw this article but I was wondering can you do that for each node, not the whole graph. – geralt Jan 04 '21 at 17:45

1 Answers1

0

You could consider the edges sorted by weight and build a dictionary that maps a node with its edges, sorted by weight in a non-increasing way.

>>> from collections import defaultdict
>>> res = defaultdict(list)
>>> for u,v in sorted(G.edges(), key=lambda x: G.get_edge_data(x[0], x[1])["weight"], reverse=True):
...     res[u].append((u,v))
...     res[v].append((u,v))
... 

Then, given a node (e.g., 0), you could get the top N (e.g., 5) weighted edges as

>>> res[0][:5]
[(0, 7), (0, 2), (0, 6), (0, 1), (0, 3)]

If you only need to do it for a node (e.g., 0), you can directly do:

>>> sorted_edges_u = sorted(G.edges(0), key=lambda x: G.get_edge_data(x[0], x[1])["weight"], reverse=True)
>>> sorted_edges_u[:5]
[(0, 7), (0, 2), (0, 6), (0, 1), (0, 3)]
abc
  • 11,579
  • 2
  • 26
  • 51