I am having a problem with numpy array I have an array A with A.shape = (2000,224,224,3). I also have an array B with B.shape = (224,224,3).
I need to insert B as the last element of A, so after inserting
A.shape = (2001,224,224,3) and A[2001] = B
I have tried np.concatenate((A,B),axis = 0) but it can't solve my problem
a = np.random.rand(2000,224,224,3)
b = np.random.rand(224,224,3)
a = np.concatenate((a,b),axis = 0)
ValueError: all the input arrays must have same number of dimensions
What I expect is
a.shape = (2001,224,224,3)
a[2001] = b
Thanks for your help!
2 Answers 2
You can throw in a new axis to make b have the same shape as a
import numpy as np
a = np.random.rand(2000,224,224,3)
b = np.random.rand(224,224,3)
a = np.concatenate((a,b[np.newaxis]))
np.all(a[-1] == b)
gives True
Comments
Shape of numpy array which are used for concatenate must be same except for the axis on which the numpy concatenation applied.
In your case, the default axis used when numpy concatenate method used in 0, As there is mismatch in the shapes of arrays used, we get error.
so reshape b array; b = b.reshape(1, 224, 224, 3) then use it in numpy concatenation,
result = np.concatenate((a,b), axis = 0)