2016-01-29 230 views
1

從這個簡單的數據幀開始:熊貓 - 根據列重塑數據幀到邊緣列表值

node t1 t2 
0 a pos neg 
1 b neg neg 
2 c neg neg 
3 d pos neg 
4 e neg pos 
5 f pos neg 
6 g neg pos 

我想建立一個EdgeList都文件讀取它作爲一個無向網絡。預期的輸出是:

b c 
a d 
a f 
d f 
e g 

所以基本上我連接兩個節點,如果他們在['t1','t2']列相同的值對。到目前爲止,我第一次嘗試以組值到一個新的列:

d['c'] = [tuple(i) for i in df[['t1','t2']].values] 

但後來我在分組用戶如我所願stucked。

編輯: 修復創建新列的錯誤。

回答

2

看一看此:

df = pd.DataFrame({'node': ['a', 'b','c', 'd', 'e', 'f', 'g'], 
       't1': ['pos', 'neg', 'neg', 'pos', 'neg', 'pos', 'neg'], 
       't2': ['neg', 'neg', 'neg', 'neg', 'pos', 'neg', 'pos']}) 

K = nx.Graph() 
K.add_nodes_from(df['node'].values) 

# Create edges 
for i, group in df.groupby(['t1', 't2'])['node']: 
    # generate all combinations without replacement 
    # from the group of similar column pairs 
    for u, v in itertools.combinations(group, 2):   
     K.add_edge(u, v) 

print(K.edges()) 

結果:[( '一個', 'd'),( '一個', 'F'),( 'C', 'B' ),( 'E', 'G'),( 'd', 'F')]

這裏的關鍵是要組通過在大熊貓同時2列。然後,您可以創建邊的所有組合以添加到圖中。