2017-09-15 1 views
0

법적 단체가 후원하거나 공동 스폰서 한 각 후보자와 가장자리로 연결되어있는 (bipartite) 방향 그래프가 있습니다. 그것으로부터, 노드가 후보가되는 첫 번째 노드로부터 투영 된 두 번째 (단일 한) 무향의 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))  
+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) 
관련 문제