Python如何在numpy中组合两个矩阵

时间:2013-11-24 19:57:19

标签: python numpy matrix

Python的新手,在numpy中苦苦挣扎,希望有人可以帮助我,谢谢!

from numpy  import *   
A = matrix('1.0 2.0; 3.0 4.0')    
B = matrix('5.0 6.0')
C = matrix('1.0 2.0; 3.0 4.0; 5.0 6.0')
print "A=",A
print "B=",B
print "C=",C

结果:

A= [[ 1.  2.]
   [ 3.  4.]]
B= [[ 5.  6.]]
C= [[ 1.  2.]
   [ 3.  4.]
   [ 5.  6.]]

问题:如何使用A和B生成C,就像在matlab C=[A;B]

中一样

4 个答案:

答案 0 :(得分:34)

使用numpy.concatenate

>>> import numpy as np
>>> np.concatenate((A, B))
matrix([[ 1.,  2.],
        [ 3.,  4.],
        [ 5.,  6.]])

答案 1 :(得分:16)

您可以使用numpy.vstack

>>> np.vstack((A,B))
matrix([[ 1.,  2.],
        [ 3.,  4.],
        [ 5.,  6.]])

答案 2 :(得分:2)

如果您想处理现有的数组C,可以在现场进行:

>>> from numpy  import *
>>> A = matrix('1.0 2.0; 3.0 4.0')
>>> B = matrix('5.0 6.0')

>>> shA=A.shape
>>> shA
(2L, 2L)
>>> shB=B.shape
>>> shB
(1L, 2L)

>>> C = zeros((shA[0]+shB[0],shA[1]))
>>> C
array([[ 0.,  0.],
       [ 0.,  0.],
       [ 0.,  0.]])

>>> C[:shA[0]]
array([[ 0.,  0.],
       [ 0.,  0.]])
>>> C[:shA[0]]=A
>>> C[shA[0]:shB[0]]=B
>>> C
array([[ 1.,  2.],
       [ 3.,  4.],
       [ 0.,  0.]])
>>> C[shA[0]:shB[0]+shA[0]]
array([[ 0.,  0.]])
>>> C[shA[0]:shB[0]+shA[0]]=B
>>> C
array([[ 1.,  2.],
       [ 3.,  4.],
       [ 5.,  6.]])

答案 3 :(得分:1)

对于高级合并(如果要合并大量矩阵,可以给它循环):

# Advanced combining
import numpy as np

# Data
A = np.matrix('1 2 3; 4 5 6')
B = np.matrix('7 8')
print('Original Matrices')
print(A)
print(B)

# Getting the size
shA=np.shape(A)
shB=np.shape(B)
rowTot=shA[0]+shB[0]
colTot=shA[1]+shB[1]
rowMax=np.max((shA[0],shB[0]))
colMax=np.max((shA[1],shB[1]))

# Allocate zeros to C
CVert=np.zeros((rowTot,colMax)).astype('int')
CHorz=np.zeros((rowMax,colTot)).astype('int')
CDiag=np.zeros((rowTot,colTot)).astype('int')

# Replace C
CVert[0:shA[0],0:shA[1]]=A
CVert[shA[0]:rowTot,0:shB[1]]=B
print('Vertical Combine')
print(CVert)

CHorz[0:shA[0],0:shA[1]]=A
CHorz[0:shB[0],shA[1]:colTot]=B
print('Horizontal Combine')
print(CHorz)

CDiag[0:shA[0],0:shA[1]]=A
CDiag[shA[0]:rowTot,shA[1]:colTot]=B
print('Diagonal Combine')
print(CDiag)

结果:

# Result
# Original Matrices
# [[1 2 3]
#  [4 5 6]]
# [[7 8]]
# Vertical Combine
# [[1 2 3]
#  [4 5 6]
#  [7 8 0]]
# Horizontal Combine
# [[1 2 3 7 8]
#  [4 5 6 0 0]]
# Diagonal Combine
# [[1 2 3 0 0]
#  [4 5 6 0 0]
#  [0 0 0 7 8]]

信用:我会编辑您的答案并实施代码中已有的内容