繁体   English   中英

如何为节点创建边缘?

[英]how to create edges for nodes?

需要在输入文件中找到每种蛋白质的程度,如下所示

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 ,我们可以使用from_pandas_edgelist函数将其转换为networkx图。

import networkx as nx
import pandas as pd

df = pd.read_csv('protein.txt', sep='\s+')
g = nx.from_pandas_edgelist(df, 'A', 'B')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM