2017-06-15 56 views
1

我想弄清楚如何迭代地追加2D数组来生成单数更大的数组。在每次迭代中,如下所示,生成16x200 ndarray:在Python中使用numpy迭代地追加ndarray阵列

Array to iteratively 'append'

对于生成新16x200阵列中的每个迭代中,我想“追加”这对先前产生的阵列,用于总共N次迭代的。例如,对于两次迭代,第一次生成的数组将是16x200,对于第二次迭代,新生成的16x200数组将被附加到第一次创建16x400大小的数组。

train = np.array([]) 
for i in [1, 2, 1, 2]: 
    spike_count = [0, 0, 0, 0] 
    img = cv2.imread("images/" + str(i) + ".png", 0) # Read the associated image to be classified 
    k = np.array(temporallyEncode(img, 200, 4)) 
    # Somehow append k to train on each iteration 

在上述嵌入代码的情况下,循环迭代4次,所以最终的列车阵列的尺寸预计为16x800。任何帮助将不胜感激,我已经对如何成功完成这一任务留下了空白。下面的代码是一个一般的情况:

import numpy as np 

totalArray = np.array([]) 
for i in range(1,3): 
    arrayToAppend = totalArray = np.zeros((4, 200)) 
    # Append arrayToAppend to totalArray somehow 

回答

0

使用numpy的hstack尝试。从文档中,hstack获取一系列数组并将它们水平堆叠以构成一个数组。

例如:

import numpy as np 

x = np.zeros((16, 200)) 
y = x.copy() 

for i in xrange(5): 
    y = np.hstack([y, x]) 
    print y.shape 

给出:

(16, 400) 
(16, 600) 
(16, 800) 
(16, 1000) 
(16, 1200) 
1

虽然可以进行concatenate在每次迭代(或“栈”的变体中的一个),它通常更快是将数组累加到列表中,并执行一次连接。列表追加更简单快捷。

alist = [] 
for i in range(0,3): 
    arrayToAppend = totalArray = np.zeros((4, 200)) 
    alist.append(arrayToAppend) 
arr = np.concatenate(alist, axis=1) # to get (4,600) 
# hstack does the same thing 
# vstack is the same, but with axis=0 # (12,200) 
# stack creates new dimension, # (3,4,200), (4,3,200) etc