Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

Array to iteratively 'append'

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
like image 912
GloveTree Avatar asked Mar 09 '23 20:03

GloveTree


1 Answers

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
like image 90
hpaulj Avatar answered Apr 26 '23 23:04

hpaulj