Python Reading from a file to create a weighted directed graph using networkx

前端 未结 1 1003
说谎
说谎 2021-02-09 02:11

I am new at python and Spyder. I am trying to read from a text file with format into a graph using networkx:

FromNodeId  ToNodeId    Weight
0   1   0.15
0   2            


        
相关标签:
1条回答
  • 2021-02-09 02:34

    You have comment first line with symbol # (read_edgelist by default skip lines start with #):

    #FromNodeId  ToNodeId    Weight
     0   1   0.15
     0   2   0.95
     0   3   0.8
    

    Then modify call of read_edgelist to define type of weight column:

    import networkx as nx
    import matplotlib.pyplot as plt
    
    g = nx.read_edgelist('./test.txt', nodetype=int,
      data=(('weight',float),), create_using=nx.DiGraph())
    
    print(g.edges(data=True))
    nx.draw(g)
    plt.show()
    

    Output:

    [(0, 1, {'weight': 0.15}), (0, 2, {'weight': 0.95}), (0, 3, {'weight':
    0.8}), (0, 4, {'weight': 0.5}), (0, 5, {'weight': 0.45}), (0, 6, {'weight': 0.35}), (0, 7, {'weight': 0.4}), (0, 8, {'weight': 0.6}), (0, 9, {'weight': 0.45}), (0, 10, {'weight': 0.7}), (1, 2, {'weight':
    0.45}), (1, 11, {'weight': 0.7}), (1, 12, {'weight': 0.6}), (1, 13, {'weight': 0.75}), (1, 14, {'weight': 0.55}), (1, 15, {'weight':
    0.1})]
    

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