Home > Software engineering >  Concatenate 2D arrays with different first dimension
Concatenate 2D arrays with different first dimension

Time:10-19

I have three numpy arrays, respectively with shape:

x1 = (30, 17437)
x2 = (30, 24131)
x3 = (30, 19782)

I would like to concatenate them and create a numpy array of dimension (30, 61350). I tried with

labels = np.concatenate((x1, x2, x3))

but I got the error:

all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 17437 and the array at index 1 has size 24131

CodePudding user response:

You can do it as shown below:

labels = np.array([x1[0], (x1[1]   x2[1]   x3[1])])
print(labels)

Output:

[   30 61350]

CodePudding user response:

You can use numpy.r_:

x1 = np.zeros((30, 17437))
x2 = np.zeros((30, 24131))
x3 = np.zeros((30, 19782))
np.r_['-1',x1,x2,x3]

Check:

>>> np.r_['-1',x1,x2,x3].shape
(30, 61350)

CodePudding user response:

You forgot to specify the axis along which the arrays will be joined. This issue is fixed easily:

labels = np.concatenate((x1, x2, x3), axis=1)
  • Related