Concat two arrays of different dimensions numpy

Question:

I am trying to concatenate two numpy arrays to add an extra column: array_1 is (569, 30) and array_2 is is (569, )

combined = np.concatenate((array_1, array_2), axis=1)

I thought this would work if I set axis=2 so it will concatenate vertically. The end should should be a 569 x 31 array.

The error I get is ValueError: all the input arrays must have same number of dimensions

Can someone help?

Thx!

Asked By: Trung Tran

||

Answers:

You can use numpy.column_stack:

np.column_stack((array_1, array_2))

Which converts the 1-d array to 2-d implicitly, and thus equivalent to np.concatenate((array_1, array_2[:,None]), axis=1) as commented by @umutto.


a = np.arange(6).reshape(2,3)
b = np.arange(2)

a
#array([[0, 1, 2],
#       [3, 4, 5]])

b
#array([0, 1])

np.column_stack((a, b))
#array([[0, 1, 2, 0],
#       [3, 4, 5, 1]])
Answered By: Psidom

You can simply use numpy‘s hstack function.

e.g.

import numpy as np

combined = np.hstack((array1,array2))
Answered By: Darshil Shah

To stack them vertically try

np.vstack((array1,array2))
Answered By: Forough Nasihati

You can convert the 1-D array to 2-D array with the same number of rows using reshape function and concatenate the resulting array horizontally using numpy’s append function.

Note: In numpy’s append function, we have to mention axis along which we want to insert the values.
If axis=0, arrays are appended vertically. If axis=1, arrays are appended horizontally.
So, we can use axis=1, for current requirement

e.g.

a = np.arange(6).reshape(2,3)
b = np.arange(2)

a
#array([[0, 1, 2],
#       [3, 4, 5]])

b
#array([0, 1])

#First step, convert this 1-D array to 2-D (Number of rows should be same as array 'a' i.e. 2)
c = b.reshape(2,1)

c
#array([[0],
        [1]])


#Step 2, Using numpy's append function we can concatenate both arrays with same number of rows horizontally

requirement = np.append((a, c, axis=1))

requirement
#array([[0, 1, 2, 0],
#       [3, 4, 5, 1]])
Answered By: Shashwat Avi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.