1

I have a data frame like :

label1 label2 amount 
 1       1     100
 1       2      20
 1       3      10 
 1       4      50
 1       5      20
 1       6     100
 2       1      20
 2       2      10 
 2       3      50
 2       4      20
 2       5     100
 2       6      20
 3       1      10 
 3       2      50
 3       3      20
 3       4     100
 3       5      20
 3       6      10 
 4       1      50
 4       2      20
 4       3      10 
 4       4      50
 4       5      20
 4       6     100
 5       1      10 
 5       2      50
 5       3      20
 5       4     100
 5       5      20
 5       6      10
 6       1      10 
 6       2      50
 6       3      20
 6       4     100
 6       5      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?

sunny
  • 253
  • 1
  • 5
  • 15

1 Answers1

2

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]))

Output:

60
60
Serenity
  • 35,289
  • 20
  • 120
  • 115
  • Thanks ! great . I think it will help me to have path length as the total amount between two selected nodes.Just I have a question , I couldn't do it by undirected Graph ? – sunny Aug 19 '17 at 04:35
  • Why not? You can but you have to check that your way exists. – Serenity Aug 19 '17 at 04:40
  • I couldn't be figured it out to have a list of path length between each two nodes, suppose I have 6 nodes, I have 35 edges but I want to have the cumulative weight between each two nodes for example 12 and 21, 13 and 31,23 and 32 ... I want to have a list of paths finally . – sunny Aug 20 '17 at 19:43
  • Sum them via output of G.edges(data=True). – Serenity Aug 20 '17 at 23:18