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
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()])