如何从tsv文件中找到节点的所有三元组(大小为3的连接组件)?

时间:2019-02-20 15:15:07

标签: python python-3.x pandas networkx

从下面给出的矩阵中,我必须建立一个网络并找到大小为3的所有已连接组件。 我使用的数据集是:

0   1   1   0   0   0   0   0   0   0   0
1   0   0   0   0   0   0   0   0   0   0
1   0   0   1   0   0   0   0   0   0   0
0   0   1   0   0   0   0   0   0   0   0
0   0   0   0   0   0   0   0   0   0   1
0   0   0   0   0   0   0   0   0   0   0
0   0   0   0   0   0   0   0   0   0   0
0   0   0   0   0   0   0   0   0   0   0
0   0   0   0   0   0   0   0   0   0   0
0   0   0   0   0   0   0   0   0   0   0
0   0   0   0   1   0   0   0   0   0   0

有人可以帮忙吗? 预期的已连接三连体将为:-

1   2   3
1   3   4
2   1   3
3   1   4

我的代码:

import networkx as nx
from itertools import chain
import csv
import numpy as np
import pandas as pd

adj = []
infile="2_mutual_info_adjacency.tsv"
df=pd.read_csv(infile,delimiter="\t",header=None)
arr=np.array(df.iloc[0:10,:])
arr1=np.array(df.iloc[:,0:10])

for i in range(arr):
  for j in range(arr1):
    if (i,j)==1:
      for k in range(j+1,arr1):
        if (i,k)==1:
          adj.append(i,j,k)
      for l in range(i+1,arr):
        if(l,j)==1:
          adj.append(i,j,l)

我们将不胜感激。预先谢谢你。

1 个答案:

答案 0 :(得分:1)

您可以使用功能connected_componets()查找所有连接的组件。随后,您可以过滤出包含三个节点的组件:

import networkx as nx
import pandas as pd
from itertools import chain

adj_matrix = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
]

df = pd.DataFrame(adj_matrix)

G = nx.from_pandas_adjacency(df)

# filter components of size 3
triplets = [c for c in nx.connected_components(G) if len(c) == 3]

triples_chain = set(chain.from_iterable(triplets))
color = ['lime' if n in triples_chain else 'pink' for n in  G.nodes()]

# jupyter notebook
%matplotlib inline
nx.draw(G, with_labels=True, node_color=color, node_size=1000)

Graph