3

I want append numpy arrays like below

A: [[1,2,3],[2,3,1],[1,4,2]] 
B: [[1,3,3],[3,3,1],[1,4,5]]
A+B = [[[1,2,3],[2,3,1],[1,4,2]],
       [[1,3,3],[3,3,1],[1,4,5]]]

How can I do this?

====================

Code copied from comment, and formatted for clarity:

X = np.empty([54, 7]) 
for seq in train_set: 
    print(seq) 
    temp = dp.set_xdata(seq) #make 2d numpy array 
    print(temp.shape) 
    X = np.row_stack((X[None], temp[None])) 
X = np.delete(X, 0, 0) 
print("X: ",X) 

ValueError: all the input arrays must have same number of dimensions. 
hpaulj
  • 221,503
  • 14
  • 230
  • 353
ukDongha
  • 63
  • 1
  • 4
  • Possible duplicate of [Append a NumPy array to a NumPy array](http://stackoverflow.com/questions/9775297/append-a-numpy-array-to-a-numpy-array) – XZ6H Jan 07 '17 at 17:05
  • It would be better to collect your `temp` in a list, and apply the `stack` once at the end. It is faster than repeated `row_stack`, and doesn't require that extra `empty` and `delete`. – hpaulj Jan 07 '17 at 17:33

1 Answers1

6

One way would be to use np.vstack on 3D extended versions of those arrays -

np.vstack((A[None],B[None]))

Another way with np.row_stack (functionally same as np.vstack) -

np.row_stack((A[None],B[None]))

And similarly with np.concatenate -

np.concatenate((A[None],B[None])) # By default stacks along axis=0

Another way would be with np.stack and specifying the axis of stacking i.e. axis=0 or skip it as that's the default axis of stacking -

np.stack((A,B))
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • here is my code. X = np.empty([54, 7]) for seq in train_set: print(seq) temp = dp.set_xdata(seq) #make 2d numpy array print(temp.shape) X = np.row_stack((X[None], temp[None])) X = np.delete(X, 0, 0) print("X: ",X) ValueError: all the input arrays must have same number of dimensions. How can i fixed it? – ukDongha Jan 07 '17 at 17:06
  • @ukDongha What are the shapes of `X` and `temp`? At which line is that error occuring? – Divakar Jan 07 '17 at 17:08
  • 2d numpy array. and second loop np.row_stack() function is error. i think it is because 3d array + 2d array. – ukDongha Jan 07 '17 at 17:10
  • @ukDongha Well you are making `X` a 3D array at the first iteration of that loop. So, at the second iteration, you are trying to stack that 3D array with a 2D array (temp). Thus, you are seeing the error. – Divakar Jan 07 '17 at 17:14
  • How can I fix it? How can I append 2d array to 3d array? – ukDongha Jan 07 '17 at 17:16
  • @ukDongha `np.vstack((3D_array, 2D_array[None]))`. – Divakar Jan 07 '17 at 17:18
  • Excellent! It is perfect! Thank you so much! – ukDongha Jan 07 '17 at 17:22