簡體   English   中英

使用Python改進從有向圖投影的無向圖的創建

[英]Improve creation of undirected graph projected from a directed one using Python

我有一個(雙向)有向圖,其中法人實體通過一條邊與它所贊助或共同贊助的每個候選人相連。 從中,我想要從第一個投影的第二個(單方),無向的G ,其中節點是候選者,連接它們的權重邊表示它們從同一法人實體一起收到錢的次數。

所有信息都編碼在一個數據幀的candidate_donator ,每個候選者都與一個元組相關聯,該元組包含誰捐贈給他。

我正在使用Networkx創建網絡,並希望優化我的實施,因為這花費了很長時間。 我的原始方法是:

candidate_donator = df.groupby('candidate').agg({'donator': lambda x: tuple(set(x))})

import itertools
candidate_pairs= list(itertools.combinations(candidate_donator .index, 2)) #creating all possible unique combinations of pair candidates ~83 M

for cpf1, cpf2 in candidate_pairs:
    donators_filter = list(filter(set(candidate_pairs.loc[cpf1]).__contains__, candidate_pairs.loc[cpf2]))
    G.add_edge(cpf1, cpf2, weight = len(donators_filter ))      

嘗試這個:

#list of donators per candidate
candidate_donator = df.groupby('candidate').agg({'donator': lambda x: tuple(set(x))})
#list of candidates per donator
donator_candidate = df.groupby('donator').agg({'candidate': lambda x: tuple(set(x))})

#for each candidate
for candidate_idx in candidate_donator.index:
    #for each donator connected to this candidate
    for donator_list in candidate_donator.loc[candidate_idx, 'donator']:
        for last_candidate in donator_list:
            #existing edge, add weight
            if G.has_edge(candidate_idx, last_candidate):
                G[candidate_idx][last_candidate] += 0.5
            #non existing edge, weight = 0.5 (every edge will be added twice)
            else:
                G.add_edge(candidate_idx, last_candidate, weight = 0.5)

暫無
暫無

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

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