Translate lists to a 2D numpy matrix
<p>I have a list of lists in python. The lists is the following:</p>

<pre><code>[[196, 242, 3], 
 [186, 302, 3], 
 [22, 377, 1],
 [196, 377, 3],
 ....
 ]
</code></pre>

<p>The first column correspond to users (1:943) and the second to items(1:1682) and their votes to items. I want to try the matrix factorization <a href="https://github.com/mnick/scikit-tensor" rel="nofollow">library</a>. Should I created a users x items matrix? If yes how can I create a matrix like that in python, with the one axis to be in size of users the other one the size of items and the values the votes of the users?</p>

<p><strong>EDIT:</strong> I check also the implementation of nmf.py which requir as input a 2D matrix and not a list or a sparse represantation.</p>

<p>You data looks like a list of lists:</p>

<pre><code>In [168]: ll = [[196, 242, 3], 
     ...:  [186, 302, 3], 
     ...:  [22, 377, 1],
     ...:  [196, 377, 3]]
</code></pre>

<p>Make an array from it - for convenience in the following operations</p>

<pre><code>In [169]: A = np.array(ll)
In [170]: ll
Out[170]: [[196, 242, 3], [186, 302, 3], [22, 377, 1], [196, 377, 3]]
In [171]: A
Out[171]: 
array([[196, 242,   3],
       [186, 302,   3],
       [ 22, 377,   1],
       [196, 377,   3]])
</code></pre>

<p>Shift the index columns to 0 base (optional)</p>

<pre><code>In [172]: A[:,:2] -= 1
</code></pre>

<p>With this it is quick and easy define a sparse matrix using the <code>coo</code> (or <code>csr</code>) format, of <code>(data, (rows, cols))</code>.  The iterative <code>dok</code> approach works, but this is faster.</p>

<pre><code>In [174]: from scipy import sparse
In [175]: M = sparse.csr_matrix((A[:,2],(A[:,0], A[:,1])), shape=(942,1681))
In [176]: M
Out[176]: 
&lt;942x1681 sparse matrix of type '&lt;class 'numpy.int32'&gt;'
    with 4 stored elements in Compressed Sparse Row format&gt;
In [177]: print(M)
  (21, 376) 1
  (185, 301)    3
  (195, 241)    3
  (195, 376)    3
</code></pre>

<p><code>M.A</code> creates a dense array from this sparse matrix.  Some code, especially in the <code>sckit-learn</code> package can use sparse matrices directly.</p>

<p>A direct way of creating the dense array is:</p>

<pre><code>In [183]: N = np.zeros((942,1681),int)
In [184]: N[A[:,0],A[:,1]]= A[:,2]
In [185]: N.shape
Out[185]: (942, 1681)
In [186]: M.A.shape
Out[186]: (942, 1681)
In [187]: np.allclose(N, M.A)   # it matches the sparse version
Out[187]: True
</code></pre>

python numpy matrix