sunny sunny - 1 month ago 15
Python Question

How to add custom function for calculating edges weights in a graph?

I have a data frame like :

label1 label2 amount
4 5 100
5 4 20
1 2 10
2 1 50
3 3 20

I've created a directed Gragh from networkx that, label1 and label2 are nodes and amount is weight of edges, I want to have the edges weights like the sum of amount between nodes for example between nodes 1 and 2 the weight calculated 60, but networkx consider 50 as weight.

is there any way to add custom function that calculate sum of amounts as weight?

Answer Source

Make directed graph from pandas dataframe. then you can calculate path length via edges data or make custom function like in this example:

import pandas as pd
import networkx as nx

# calc length of custom path via nodes list
# path have to be connected
def path_length(G, nodes):
    w = 0
    for ind,nd in enumerate(nodes[1:]):
        prev = nodes[ind]
        w += G[prev][nd]['amount']
    return w

# construct directed graph
df = pd.DataFrame({'label1':[4,5,1,2,3], 
 'label2':[5,4,2,1,3], 'amount':[100,200,10,50,20]})
G=nx.from_pandas_dataframe(df, 'label1', 'label2', 'amount',nx.DiGraph())

# calc amount of path from edges data
w = 0
for d in G.edges([1,2], data=True):
    w += d[2]['amount']
print (w)

# calc path length by custom function
print(path_length(G, [1,2,1]))