如何添加自定义函数来计算图形中的边权重? [英] How to add custom function for calculating edges weights in a graph?

查看:180
本文介绍了如何添加自定义函数来计算图形中的边权重?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,如:

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

我从networkx创建了一个定向Gragh,label1和label2是节点,数量是边缘的权重,我想让边缘的权重像节点之间的数量之和一样,例如节点1和2之间的权重60,但networkx认为50为权重.

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?

推荐答案

从pandas数据框中生成有向图.那么您可以通过边数据来计算路径长度,或者像以下示例一样创建自定义函数:

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

输出:

60
60

这篇关于如何添加自定义函数来计算图形中的边权重?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆