2017-09-15 24 views
0

我有一個(雙向)有向圖,其中法律實體通過邊緣與其贊助或共同贊助的每位候選人連接。從它開始,我想要第二個(單一的),無向的G,其中第一個節點是候選人,連接它們的加權邊表示他們從同一個法律實體那裏收到了多少錢。使用Python改進從定向人物投影的無向圖的創建

所有信息都編碼在一個數據框中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))  
+1

絕對預先計算的邊緣,然後將它們添加一氣呵成的曲線圖。每次向圖中添加邊時,都會複製整個圖形對象。 – Paul

+0

另外,您的總獨特捐助者與總(獨特)候選人的比例是多少? – Paul

回答

1

試試這個:

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