Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding maximum weighted edge in a networkx graph in python

I want to find 'n' maximum weighted edges in a networkx graph. How can it be achieved. I have constructed a graph as follows :

g_test = nx.from_pandas_edgelist(new_df, 'number', 'contactNumber', edge_attr='callDuration')

Now, I want to find top 'n' edge weights, i.e. top 'n' callDurations. I also want to analyse this graph to find trends from it. Please help me how can this be achieved.

like image 418
Anand Nautiyal Avatar asked Sep 21 '18 09:09

Anand Nautiyal


2 Answers

If your graph is stored as g you can access its edges, including their attributes using:

g.edges(data=True)

This returns a list of tuples. The first two entries are the nodes, and the third entry is a dictionary of the attributes, looking like this:

[(a,b,{"callDuration":10}),(a,c,{"callDuration":7})]

You can sort this list based the callDuration attribute like this:

sorted(g.edges(data=True),key= lambda x: x[2]['callDuration'],reverse=True)

Note we use reverse to see the largest callDuration edges first.

I'm afraid your second question is very broad - you can do a lot of things with networks! Have a look at some tutorials like this one: https://programminghistorian.org/en/lessons/exploring-and-analyzing-network-data-with-python

like image 74
Johannes Wachs Avatar answered Nov 09 '22 12:11

Johannes Wachs


Let's try:

max(dict(g_test.edges).items(), key=lambda x: x[1]['callduration'])

To find the maximum weight edge in this graph network.

like image 5
Scott Boston Avatar answered Nov 09 '22 12:11

Scott Boston