title: How to manually create a sparse matrix in Python
body: <p>I have a text file containing data representing a sparse matrix with the following format:</p>
  
  <pre><code>0 234 345
  0 236 
  0 345 365 465
  0 12 35 379
  </code></pre>
  
  <p>The data is used for a classification task and each row can be considered a feature vector. The first value in each row represents a label, the values following it represent the presence of individual features.</p>
  
  <p>I'm trying to create a sparse matrix with these values (to use in a machine learning task with scikit learn). I've found and read the <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/sparse.html" rel="nofollow noreferrer">scipy.sparse documentation</a> but I'm failing to understand how to incrementally build up a sparse matrix with source data like this. </p>
  
  <p>The examples I've found so far show how to take a dense matrix and convert it, or how to create a native sparse matrix with contrived data, but no examples that have helped me here. I did find this related SO question (<a href="https://stackoverflow.com/questions/20583381/building-and-updating-a-sparse-matrix-in-python-using-scipy">Building and updating a sparse matrix in python using scipy</a>), but the example assumes you know the max COL, ROW sizes, which I don't, so that data type doesn't seem appropriate.</p>
  
  <p>So far I have the following code to read the document and parse the values into something that seems reasonable:</p>
  
  <pre><code>def get_sparse_matrix():
      matrix = []
      with open("data.dat", 'r') as f:
          for i, line in enumerate(f):
              row = line.strip().split()
              label = row[0]
              features = entry[1:]
              matrix.append([(i, col) for col in features])
  
      sparse_matrix = #magic happens here
  
      return sparse_matrix
  </code></pre>
  
  <p>So questions are, </p>
  
  <ul>
  <li>What is the appropriate sparse matrix type to use here?</li>
  <li>Am I heading in the right direction with the code I have?</li>
  </ul>
  
  <p>Any help is greatly appreciated.</p>