Python: Concatenating scipy sparse matrix
<p>I am trying to Concatenate 2 sparse matrix by the help of hstack function. xtrain_cat is the output of DictVectorizer(encodes categorical values) and xtrain_num is a pandas cvs file.</p>

<pre><code>    xtrain_num = sparse.csr_matrix(xtrain_num)
    print type(xtrain_num)
    print xtrain_cat.shape
    print xtrain_num.shape
    x_train_data = hstack(xtrain_cat,xtrain_num)
</code></pre>

<p>Error :</p>

<pre><code>(1000, 2778)
&lt;class 'scipy.sparse.csr.csr_matrix'&gt;
&lt;class 'scipy.sparse.csr.csr_matrix'&gt;
(1000, 2778)
(1000, 968)
Traceback (most recent call last):
  File "D:\Projects\Zohair\Bosch\Bosch.py", line 360, in &lt;module&gt;
    x_train_data = hstack(xtrain_cat,xtrain_num)
  File "C:\Users\Public\Documents\anaconda2\lib\site-packages\scipy\sparse\construct.py", line 464, in hstack
    return bmat([blocks], format=format, dtype=dtype)
  File "C:\Users\Public\Documents\anaconda2\lib\site-packages\scipy\sparse\construct.py", line 547, in bmat
    raise ValueError('blocks must be 2-D')
ValueError: blocks must be 2-D
</code></pre>

<p>Can someone identify what is the probelm</p>

<p>You should try:</p>

<pre><code>x_train_data = hstack((xtrain_cat,xtrain_num))
</code></pre>

<p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.hstack.html" rel="nofollow">It takes a sequence</a>:</p>

<blockquote>
  <p><strong>blocks</strong> sequence of sparse matrices with compatible shapes</p>
</blockquote>

<hr>

<p>When I define <code>a</code> to be a sparse matrix, I can verify your error when I omit it (and correct it when I add it):</p>

<pre><code>In [19]: sparse.hstack(a, a)
    ---------------------------------------------------------------------------
ValueError                                Traceback (most recent     call last)
&lt;ipython-input-19-7c450ab4fda0&gt; in &lt;module&gt;()
----&gt; 1 sparse.hstack(a, a)

/usr/local/lib/python2.7/dist-packages/scipy/sparse/construct.pyc in hstack(blocks, format, dtype)
    454 
    455     """
--&gt; 456     return bmat([blocks], format=format, dtype=dtype)
    457 
    458 

/usr/local/lib/python2.7/dist-packages/scipy/sparse/construct.pyc in     bmat(blocks, format, dtype)
    537 
    538     if blocks.ndim != 2:
--&gt; 539         raise ValueError('blocks must be 2-D')
    540 
    541     M,N = blocks.shape

ValueError: blocks must be 2-D

In [20]: sparse.hstack((a, a))
Out[20]: 
&lt;3x8 sparse matrix of type '&lt;type 'numpy.float64'&gt;'
    with 0 stored elements in COOrdinate format&gt;
</code></pre>

python scipy sparse-matrix