Efficiently create adjacency matrix from network graph (vice versa) Python NetworkX

前端 未结 2 1883
清歌不尽
清歌不尽 2021-02-10 09:01

I\'m trying to get into creating network graphs and generating sparse matrices from them. From the wikipedia Laplacian matrix example, I decided to try and recreat

相关标签:
2条回答
  • 2021-02-10 09:41

    I was confronted with the same problem, and found a solution. We can use the function from_numpy_matrix, which is depicted in official website http://networkx.github.io/documentation/networkx-1.7/reference/generated/networkx.convert.from_numpy_matrix.html. Pay attention that the input data usually needs to be modified by numpy.matrix(). The example given is that:

        import numpy
        A=numpy.matrix([[1,1],[2,1]])
        G=nx.from_numpy_matrix(A)
    

    It's really useful.

    0 讨论(0)
  • 2021-02-10 09:51

    How to convert from graph to adjacency matrix:

    import scipy as sp
    import networkx as nx
    G=nx.fast_gnp_random_graph(100,0.04)
    adj_matrix = nx.adjacency_matrix(G)
    

    Here's the documentation.

    And from adjacency matrix to graph:

    H=nx.Graph(adj_matrix)  #if it's directed, use H=nx.DiGraph(adj_matrix)
    

    Here's the documentation.

    0 讨论(0)
提交回复
热议问题