Fabio
Fabio

Reputation: 645

Concatenate 2D arrays with different first dimension

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

Upvotes: 3

Views: 900

Answers (3)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79580

You can do it as shown below:

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

Output:

[   30 61350]

Upvotes: 3

sgraaf
sgraaf

Reputation: 66

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)

Upvotes: 3

mozway
mozway

Reputation: 262304

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)

Upvotes: 1

Related Questions