需要查找输入文件中每种蛋白质的程度,如下所示
A B
a b
c d
a c
c b
我使用 networkx 来获取节点。如何在创建的节点上使用输入文件创建边?
法典:
import pandas as pd
df = pd.read_csv('protein.txt',sep='t', index_col =0)
df = df.reset_index()
df.columns = ['a', 'b']
distinct = pd.concat([df['a'], df['b']]).unique()
import networkx as nx
G=nx.Graph()
nodes= []
for i in distinct:
node=G.add_node(1)
nodes.append(node)
从networkx
文档中,先在循环中使用add_edge
或收集边缘,然后使用add_edges_from
:
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> e = (1,2)
>>> G.add_edge(1, 2) # explicit two-node form
>>> G.add_edge(*e) # single edge as tuple of two nodes
>>> G.add_edges_from( [(1,2)] ) # add edges from iterable container
然后G.degree()
给你节点的程度。
起初,函数 read_csv
被错误地用于读取输入文件。列由空格分隔,而不是制表符,因此sep
应's+'
而不是't'
。此外,输入文件中没有索引列,因此不应将参数 index_col
设置为 0
。
将输入文件正确读取到DataFrame
后,我们可以使用函数将其转换为networkx
图 from_pandas_edgelist
.
import networkx as nx
import pandas as pd
df = pd.read_csv('protein.txt', sep='s+')
g = nx.from_pandas_edgelist(df, 'A', 'B')