4
votes

I have an edge-list, it consists of two columns, I want to create a weighted directed graph such that for each row in the edge-list a directed edge with weight one goes from node in column one to node in column two. if the same row appears more than once in the edge-list it should increase the weight by one for each time it appears.

I'm using Python Networkx library how can I do this?

1

1 Answers

10
votes

You can use Counter to count the number of duplicate edges in order to generate weight that is passed to DiGraph:

import networkx as nx
from collections import Counter

EDGES = [
    ('A', 'B'),
    ('B', 'C'),
    ('A', 'C'),
    ('C', 'D'),
    ('A', 'B')
]

g = nx.DiGraph((x, y, {'weight': v}) for (x, y), v in Counter(EDGES).items())
print(*g.edges(data=True), sep='\n')

Output:

('A', 'B', {'weight': 2})
('A', 'C', {'weight': 1})
('C', 'D', {'weight': 1})
('B', 'C', {'weight': 1})

In above Counter returns (edge, count) tuples. Note that edges passed to Counter must be hashable.

>>> edges = list(Counter(EDGES).items())
>>> edges
[(('A', 'B'), 2), (('B', 'C'), 1), (('C', 'D'), 1), (('A', 'C'), 1)]

Then generator expression is used to yield edges in a format that DiGraph expects:

>>> params = list((x, y, {'weight':v}) for (x,y), v in edges)
>>> params
[('A', 'B', {'weight': 2}), ('B', 'C', {'weight': 1}), ('C', 'D', {'weight': 1}), ('A', 'C', {'weight': 1})]