2017-06-15 115 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