Python/NetworkX: Add Weights to Edges by Frequency of Edge Occurance

后端 未结 1 931
南笙
南笙 2020-12-31 21:11

I have a MultiDiGraph created in networkx for which I am trying to add weights to the edges, after which I assign a new weight based on the frequency/count of t

相关标签:
1条回答
  • 2020-12-31 22:11

    Try this on for size.

    Note: I added a duplicate of an existing edge, just to show the behavior when there are repeats in your multigraph.

    from collections import Counter
    c = Counter(g.edges())  # Contains frequencies of each directed edge.
    
    for u, v, d in g.edges(data=True):
        d['weight'] = c[u, v]
    
    print(list(g.edges(data=True)))
    #[(340, 269, {'weight': 1}),
    # (340, 340, {'weight': 1}),
    # (269, 340, {'weight': 1}),
    # (398, 279, {'weight': 1}),
    # (69, 28, {'weight': 1}),
    # (382, 27, {'weight': 1}),
    # (27, 285, {'weight': 2}),
    # (27, 285, {'weight': 2}),
    # (120, 422, {'weight': 1}),
    # (422, 217, {'weight': 1}),
    # (217, 340, {'weight': 1}),
    # (458, 442, {'weight': 1}),
    # (291, 431, {'weight': 1}),
    # (68, 27, {'weight': 1}),
    # (112, 269, {'weight': 1})]
    

    Edit: To visualize the graph with edge weights as thicknesses, use this:

    nx.draw_networkx(g, width=[d['weight'] for _, _, d in g.edges(data=True)])
    
    0 讨论(0)
提交回复
热议问题