My program creates a numpy array within a for loop. For example it creates array with shape (100*30*10)
, then (160*30*10)
and then may be (120*30*10)
. I have to append the above to an empty numpy array such that , at the end of the loop, it will be a numpy array with shape (380*30*10)
(i.e sum of 100+160+120) . The second and third dimension doesnt change in the numpy array.
How can I do the above in python. I tried the following.
np_model = np.append(np_model,np_temp1)
print("Appended model shape is",np_model.shape)
np_label = np.append(np_label,np_temp2)
print("Appended label shape is",np_label.shape)
The np_model
is an empty array which I have defined as np_model = np.empty(1,30,10)
and np_label as np_label = np.empty(1 ,str)
np_temp1
corresponds to array within each for loop like 100*30*10
,120*30*10
etc and np_temp2
is a string with "item1","item2" etc
The np_label
is a string numpy array with 1 label corresponding to np_temp1.shape[0]
. But the result I get in np_model is flattened array with size 380*30*10
= 1140000
Any help is appreciated.
you can use numpy concatenate
function, append the output numpy(s) to a list and then feed it to the concatenate
function:
empty_list = []
x = np.zeros([10, 20, 4])
y = np.zeros([12, 20, 4])
empty_list.append(x)
empty_list.append(y)
z = np.concatenate(empty_list, axis=0)
print(x.shape, y.shape, z.shape)
(10, 20, 4) (12, 20, 4) (22, 20, 4)