2013-06-02 19 views
6

私は2つのcsr_matrix,uniFeatureおよびbiFeatureを持っています。Pythonで2つの行列を連結する方法は?

私は新しいマトリックスがほしいFeature = [uniFeature, biFeature]です。しかし、私が直接この方法で連結すると、行列Featureがリストであるというエラーがあります。どのようにして行列連結を達成することができ、同じタイプの行列、すなわちcsr_matrixを得ることができますか?

そして、私が連結した後、これを行う場合には動作しません:Feature = csr_matrix(Feature) それはエラーを与える:

Traceback (most recent call last): 
    File "yelpfilter.py", line 91, in <module> 
    Feature = csr_matrix(Feature) 
    File "c:\python27\lib\site-packages\scipy\sparse\compressed.py", line 66, in __init__ 
    self._set_self(self.__class__(coo_matrix(arg1, dtype=dtype))) 
    File "c:\python27\lib\site-packages\scipy\sparse\coo.py", line 185, in __init__ 
    self.row, self.col = M.nonzero() 
TypeError: __nonzero__ should return bool or int, returned numpy.bool_ 

答えて

15

scipy.sparseモジュールは機能hstackvstackが含まれています。例えば

In [44]: import scipy.sparse as sp 

In [45]: c1 = sp.csr_matrix([[0,0,1,0], 
    ...:      [2,0,0,0], 
    ...:      [0,0,0,0]]) 

In [46]: c2 = sp.csr_matrix([[0,3,4,0], 
    ...:      [0,0,0,5], 
    ...:      [6,7,0,8]]) 

In [47]: h = sp.hstack((c1, c2), format='csr') 

In [48]: h 
Out[48]: 
<3x8 sparse matrix of type '<type 'numpy.int64'>' 
    with 8 stored elements in Compressed Sparse Row format> 

In [49]: h.A 
Out[49]: 
array([[0, 0, 1, 0, 0, 3, 4, 0], 
     [2, 0, 0, 0, 0, 0, 0, 5], 
     [0, 0, 0, 0, 6, 7, 0, 8]]) 

In [50]: v = sp.vstack((c1, c2), format='csr') 

In [51]: v 
Out[51]: 
<6x4 sparse matrix of type '<type 'numpy.int64'>' 
    with 8 stored elements in Compressed Sparse Row format> 

In [52]: v.A 
Out[52]: 
array([[0, 0, 1, 0], 
     [2, 0, 0, 0], 
     [0, 0, 0, 0], 
     [0, 3, 4, 0], 
     [0, 0, 0, 5], 
     [6, 7, 0, 8]]) 
+0

本当にありがとうございました!私が必要とするもの –

+0

TypeError:vstack()は予期しないキーワード引数 'format'を持っています – Moh

+0

解決済み:問題は次のとおりです: scipy.parseモジュールをインポートする代わりに、scipy – Moh

関連する問題