Reputation: 451
I am unable to find an equivalent conversion of graph_from_data_frame present in R into something in Python
What I have done is :
graph_from_data_frame(d = dataframe_1[,c("ID_TO","ID_FROM")], directed = TRUE, vertices = sort(unique(unlist(dataframe_1))))
Output of the above :
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)...
What i tried in python is the following :
# Convert dataframe to matrix
edges = dataframe_1.as_matrix(columns=None)
# create directed graph
MAP = Graph.TupleList(directed=True, edges = edges)
This gave me below output, which is incorrect (i am getting the output reversed) probably because I was not able to do a sort(unique(unlist())) variant in python. But i am unsure. Output from python code :
IGRAPH DN-- 339 201 --
+ attr: name (v)
+ edges (vertex names):
46627->46753, 46642->46737, 46629->46753, 46629->46737, 46600->46646
I came to know that there is no direct variant of graph_from_data_frame in R into anything in Python, but any lead to this approach and this result is appreciated.
Sample data from dataframe :
ID_FROM ID_TO
0 46627 46753
1 46642 46737
2 46629 46753
3 46629 46737
4 46600 46646
5 46552 46633
I have gone through many results from google differentiating about IGRAPH in R vs Python but nothing helped to the sue-case that I am working on.
Upvotes: 2
Views: 1003
Reputation: 23129
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)
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)
Upvotes: 2