Create a matrix from a text file - python

前端 未结 4 1546
清歌不尽
清歌不尽 2021-01-13 16:32

I would like to create a matrix from a three column file. I am sure it\'s something extremely easy, but I just do not understand how it needs to be done. Please be gentle, I

4条回答
  •  别那么骄傲
    2021-01-13 17:14

    You're matrix seems to resember an adjacency matrix of a graph.

    I find the answer with pandas much more concise and elegant. Here's my attempt without adding pandas as an additional dependency.

    
    f = open('.txt', 'r');
    
    EdgeKey = namedtuple("EdgeKey", ["src", "dst"])
    
    g = dict()
    for line in f:
    
        elems = line.split(' ');
        key = EdgeKey(src=elems[0], dst=elems[1])
        g[key] = elems[2]
        key_rev = EdgeKey(src=elems[1], dst=elems[0]) # g[A, B] == g[B, A]
        g[key_rev] = elems[2]
    
    vertices = set()
    for src, dst in g.keys():
        vertices.add(src)
        vertices.add(dst)
    
    vertices = list(vertices)
    vertices.sort()
    
    # create adjacency matrix
    mat  = np.zeros((len(vertices), len(vertices)))
    for s, src in enumerate(vertices):
        for d, dst in enumerate(vertices):
            e = EdgeKey(src=src, dst=dst)
            if e in g:
                mat[s, d] = int(g[e])
    
    # print adjacency matrix
    print ' ' , ' '.join(vertices) # print header
    for i, row in enumerate(mat):
        print vertices[i], ' '.join([str(int(c)) for c in row.tolist()])
    

提交回复
热议问题