簡體   English   中英

乘和加權重networkx圖python

[英]Multiplying and adding weights networkx graph python

之前,曾問過一個有關在networkx中乘以權重以找到有向圖中節點總數的問題。 如果兩個節點之間只有一條路徑,則提供的解決方案會很好,但如果路徑多,則失敗。 一個簡單的例子:

import pandas as pd
data = pd.DataFrame({'shop': ['S1', 'S1', 'S2', 'S2', 'S3'],
                     'owner': ['S2', 'S3', 'O1', 'O2', 'O1'],
                     'share': [0.8,   0.2,  0.5,  0.5, 1.0]})
  owner  shop  share
0    S2   S1    0.8
1    S3   S1    0.2
2    O1   S2    0.5
3    O2   S2    0.5
4    O1   S3    1.0

創建圖:

import networkx as nx    
G = nx.from_pandas_edgelist(data,'shop','owner',edge_attr = ('share'), 
                               create_using=nx.DiGraph())

pos=nx.spring_layout(G, k = 0.5, iterations = 20)
node_labels = {node:node for node in G.nodes()}
nx.draw_networkx(G, pos, labels = node_labels, arrowstyle = '-|>',
                 arrowsize = 20,  font_size = 15, font_weight = 'bold')

在此處輸入圖片說明

為了獲得O1在S1中的份額,需要將2條路徑相乘然后相加。 以前的解決方案無法做到這一點。 有辦法嗎?

您可以通過以下方式修改以前的解決方案:

from operator import mul

import pandas as pd
import networkx as nx
from functools import reduce

data = pd.DataFrame({'shop': ['S1', 'S1', 'S2', 'S2', 'S3'],
                     'owner': ['S2', 'S3', 'O1', 'O2', 'O1'],
                     'share': [0.8,   0.2,  0.5,  0.5, 1.0]})

G = nx.from_pandas_edgelist(data,'shop','owner',edge_attr = ('share'),
                               create_using=nx.DiGraph())

owners = set(data['owner'])
shops  = set(data['shop'])


result = []
summary = {}
for shop in shops:
    for owner in owners:
        for path in nx.all_simple_paths(G, shop, owner):
            share = reduce(mul, (G[start][end]['share'] for start, end in zip(path[:-1], path[1:])), 1)
            summary[(owner, shop)] = summary.get((owner, shop), 0) + share


summary = pd.DataFrame.from_dict(summary, orient = 'index', columns = 'share'.split())
print(summary)

產量

          share
(O2, S2)    0.5
(O2, S1)    0.4
(S3, S1)    0.2
(O1, S2)    0.5
(O1, S3)    1.0
(O1, S1)    0.6
(S2, S1)    0.8

該行:

share = reduce(mul, (G[start][end]['share'] for start, end in zip(path[:-1], path[1:])), 1)

計算特定路徑的份額。 然后,使用下一行在所有路徑上匯總此份額:

summary[(owner, shop)] = summary.get((owner, shop), 0) + share

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM