Finding maximum weighted edge in a networkx graph in python
Asked Answered
C

2

6

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.

Cryosurgery answered 21/9, 2018 at 9:19 Comment(0)
S
10

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

Swagerty answered 21/9, 2018 at 13:42 Comment(0)
P
5

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.

Prisage answered 22/9, 2018 at 0:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.