简体   繁体   中英

convert bipartite graph to adjacency matrix python

I'm trying to convert edge list which is in the following format

data = [('a', 'developer'),
         ('b', 'tester'),
        ('b', 'developer'),
         ('c','developer'),
         ('c', 'architect')]

where the adjacency matrix will be in the form of

      developer     tester    architect
a        1            0          0
b        1            1          0
c        1            0          1

I want to store the matrix in the following format

 1    0    0
 1    1    0
 1    0    1

Any help is highly appreciated

This can be done easily with networkx :

from operator import itemgetter

import networkx as nx
from networkx.algorithms.bipartite import biadjacency_matrix

def to_adjacency_matrix(data):
    g = nx.DiGraph()
    g.add_edges_from(data)
    partition_1 = set(map(itemgetter(0), data))
    return biadjacency_matrix(g, partition_1).toarray()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM