title: Transforming a 3 Column Matrix into an N x N Matrix in Numpy
body: <p>I have a 2D <code>numpy</code> array with 3 columns. Columns 1 and 2 are a list of connections between ID's. Column 3 is a the strength of that connection. I would like to transform this 3 column matrix into a weighted <a href="https://en.wikipedia.org/wiki/Adjacency_matrix" rel="nofollow">adjacency matrix</a> (an N x N matrix where cells represent the strength of connection between each ID). </p>
  
  <p>I have already done this in my code below. <code>matrix</code> is the 3 column 2D array and <code>t1</code> is the weighted adjacency matrix. My problem is this code is very slow because I am using nested for loops. I am familiar with the <code>pandas</code> function <code>melt</code> which does this, but I am not able to use <code>pandas</code>. Is there a faster implementation not using <code>pandas</code>? </p>
  
  <pre><code>import numpy as np
  a = np.arange(2000)
  np.random.shuffle(a)
  b = np.arange(2000)
  np.random.shuffle(b)
  c = np.random.rand(2000,1)
  
  matrix = np.column_stack((a,b,c))
  
  #get unique value list of nm
  flds = list(np.unique(matrix[:,0]))
  flds.extend(list(np.unique(matrix[:,1])))
  flds = np.asarray(flds)
  flds = np.unique(flds)
  
  #make lookup dict
  lookup = dict(zip(np.arange(0,len(flds)), flds))
  lookup_rev = dict(zip(flds, np.arange(0,len(flds))))
  
  #make empty n by n matrix with unique lists
  t1 = np.zeros([len(flds) , len(flds)])
  
  #map values into the n by n matrix and make the rest 0
  '''this takes a long time to run'''
  #iterate through rows
  for i in np.arange(0,len(lookup)):
      #iterate through columns
      for k in np.arange(0,len(lookup)):
          val = matrix[(matrix[:,0] == lookup[i]) &amp; (matrix[:,1] == lookup[k])][:,2]  
          if val:
              t1[i,k] = sum(val)
  </code></pre>