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. 
2
  • Possible duplicate of Append a NumPy array to a NumPy array Commented Jan 7, 2017 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. Commented Jan 7, 2017 at 17:33

1 Answer 1

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))
Sign up to request clarification or add additional context in comments.

7 Comments

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 What are the shapes of X and temp? At which line is that error occuring?
2d numpy array. and second loop np.row_stack() function is error. i think it is because 3d array + 2d array.
@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.
How can I fix it? How can I append 2d array to 3d array?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.