在python中连接许多数组

时间:2017-03-26 08:13:30

标签: python arrays numpy

我有这个代码用于连接两个数组。

import numpy as np
from hmmlearn import hmm
model = hmm.MultinomialHMM(n_components=3, n_iter=10,algorithm='map',tol=0.00001)
sequence3 = np.array([[2, 1, 0, 1]]).T
sequence4 = np.array([[2, 1, 0, 1, 1]]).T
sample = np.concatenate([sequence3, sequence4])
lengths = [len(sequence3), len(sequence4)]
model.fit(sample,lengths)

它正常工作。但现在如果我有两个以上的数组。我们来说我有10个阵列。我怎么能做同样的过程?

import numpy as np
from hmmlearn import hmm
model = hmm.MultinomialHMM(n_components=3, n_iter=10,algorithm='map',tol=0.00001)
sample = np.array([])
lengths = []
for i in range(1:10)
    ?????????????
model.fit(sample,lengths)

2 个答案:

答案 0 :(得分:1)

为了连接多个数组,只需将数组与所有先前数组的串联连接起来。

{{1}}

答案 1 :(得分:0)

您可以使用vstack

即,

  

如果tup包含数组,则等效于np.concatenate(tup,axis = 0)   至少是二维的。

将数组存储为列表,例如array_list

print np.vstack(array_list) 

样品:

import numpy as np
sequence3 = np.array([[2, 1]]).T
sequence4 = np.array([[2, 5]]).T
sequence5 = np.array([[4, 5]]).T
sequence6 = np.array([[6, 7]]).T
array_list=[sequence3,sequence4,sequence5,sequence6]
sample = np.concatenate([sequence3, sequence4])
lengths = [len(sequence3), len(sequence4)]
print np.vstack(array_list)

[[2]
 [1]
 [2]
 [5]
 [4]
 [5]
 [6]
 [7]]

希望它有所帮助!