Interface between networkx and igraph

前端 未结 5 1090
被撕碎了的回忆
被撕碎了的回忆 2020-12-29 08:30

I\'ve been working with networkx for quite some time now and it\'s been serving my purposes quite well with minimal tweaks until recently when I started looking into communi

5条回答
  •  攒了一身酷
    2020-12-29 08:57

    As I try to store names of nodes/edges on both igraph or nx, this is my one-liner version which also transfers nodes names while transferring from igraph object, g, to nx:

    G = nx.from_edgelist([(names[x[0]], names[x[1]])
                          for names in [g.vs['name']] # simply a let
                          for x in g.get_edgelist()], nx.DiGraph())
    

    And the reverse way if G, a nx object, is given but an igraph object is needed:

    g = igraph.Graph.TupleList(G.edges(), directed=True)
    

    Of course these are not complete transfer as other node attributes and also edge attribute transfers are missing but I hope would be useful when you don't have them.


    More verbose version that you have more control while transferring, from igraph to nx:

    G = nx.DiGraph()
    names = g.vs['name']
    G.add_nodes_from(names)
    G.add_edges_from([(names[x[0]], (names[x[1]])) for x in g.get_edgelist()])
    

    From nx to igraph:

    g = igraph.Graph(directed=True)
    g.add_vertices(G.nodes())
    g.add_edges(G.edges())
    

    (also posted here)

提交回复
热议问题