简体   繁体   English

在Python中使用numpy迭代地附加ndarray数组

[英]Iteratively appending ndarray arrays using numpy in Python

I am trying to figure out how to iteratively append 2D arrays to generate a singular larger array. 我试图找出如何迭代地附加2D数组以生成单个更大的数组。 On each iteration a 16x200 ndarray is generated as seen below: 在每次迭代中,生成一个16x200的ndarray,如下所示:

数组迭代'追加'

For each iteration a new 16x200 array is generated, I would like to 'append' this to the previously generated array for a total of N iterations. 对于每次迭代,生成一个新的16x200数组,我想将此“追加”到先前生成的数组中,总共N次迭代。 For example for two iterations the first generated array would be 16x200 and for the second iteration the newly generated 16x200 array would be appended to the first creating a 16x400 sized array. 例如,对于两次迭代,第一次生成的数组将是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

In the case of the above embedded code the loop iterates 4 times so the final train array is expected to be 16x800 in size. 在上述嵌入代码的情况下,循环迭代4次,因此预期最终列车阵列的大小为16x800。 Any help would be greatly appreciated, I have drawn a blank on how to successfully accomplish this. 任何帮助将不胜感激,我已经在如何成功实现这一点上画了一个空白。 The code below is a general case: 以下代码是一般情况:

import numpy as np

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

While it is possible to perform a concatenate (or one of the 'stack' variants) at each iteration, it is generally faster to accumulate the arrays in a list, and perform the concatenate once. 虽然可以在每次迭代时执行concatenate (或“堆栈”变体之一),但通常在列表中累积数组并执行连接一次会更快。 List append is simpler and faster. 列表追加更简单,更快捷。

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

Try using numpy hstack . 尝试使用numpy hstack From the documention, hstack takes a sequence of arrays and stack them horizontally to make a single array. 从文档中,hstack采用一系列数组并将它们水平堆叠以形成单个数组。

For example: 例如:

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

Gives: 得到:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM