IGRAPH从R代码转换为Python变体

时间:2017-02-17 07:00:53

标签: python r igraph

我无法找到R中存在的graph_from_data_frame等效转换为Python中的内容

我所做的是:

graph_from_data_frame(d = dataframe_1[,c("ID_TO","ID_FROM")], directed = TRUE, vertices = sort(unique(unlist(dataframe_1))))

以上输出:

IGRAPH DN-- 195 201 -- 
+ attr: name (v/c)
+ edges (vertex names):
 [1] 46753->46627 46737->46642 46753->46629 46737->46629 46646->46600  enter code here... (and so on)...

我在python中尝试的是以下内容:

# Convert dataframe to matrix
edges = dataframe_1.as_matrix(columns=None)
# create directed graph
MAP = Graph.TupleList(directed=True, edges = edges)  

这给了我下面的输出,这是不正确的(我得到输出反转)可能是因为我无法在python中进行排序(unique(unlist()))变体。但我不确定。 从python代码输出:

IGRAPH DN-- 339 201 --
+ attr: name (v)
+ edges (vertex names):
46627->46753, 46642->46737, 46629->46753, 46629->46737, 46600->46646

我开始知道R中没有 graph_from_data_frame 直接变换为Python中的任何内容,但任何导致此方法的结果都会受到赞赏。

来自dataframe的示例数据:

 ID_FROM       ID_TO
0    46627          46753
1    46642          46737
2    46629          46753
3    46629          46737
4    46600          46646
5    46552          46633

我已经通过google在R与Python中区分IGRAPH的许多结果,但没有任何帮助我正在处理的案件。

1 个答案:

答案 0 :(得分:1)

R代码

library(igraph)
dataframe_1 <- read.table(text='     ID_FROM        ID_TO
                                0    46627          46753
                                1    46642          46737
                                2    46629          46753
                                3    46629          46737
                                4    46600          46646
                                5    46552          46633', header=TRUE)
g <- graph_from_data_frame(d = dataframe_1[,c("ID_TO","ID_FROM")], directed = TRUE, vertices = sort(unique(unlist(dataframe_1))))
plot(g)

enter image description here

Python代码

from igraph import *
import pandas as pd

dataframe_1 = pd.DataFrame({'ID_FROM':[46627, 46642, 46629, 46629, 46600, 46552], 'ID_TO':[46753,46737,46753,46737,46646,46633]})
#print dataframe_1
g = Graph(directed=True)
for index, row in dataframe_1.iterrows():
   g.add_vertex(str(row['ID_FROM']))
   g.add_vertex(str(row['ID_TO']))
   g.add_edge(str(row['ID_FROM']), str(row['ID_TO'])) 
g.vs["label"] = g.vs["name"]
plot(g)

enter image description here