2017-09-15 23 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)