我有一个数据框,如:
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是节点,amount是边缘的权重,我希望边缘权重像节点之间的数量之和,例如在节点1和节点2之间重量计算60,但networkx认为50为重量。
有没有办法添加自定义函数来计算金额总和作为重量?
答案 0 :(得分:2)
从pandas数据帧制作有向图。然后你可以通过边缘数据计算路径长度或者像这个例子那样制作自定义函数:
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