简体   繁体   中英

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. On each iteration a 16x200 ndarray is generated as seen below:

数组迭代'追加'

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. 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.

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. 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. 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 . From the documention, hstack takes a sequence of arrays and stack them horizontally to make a single array.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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