nekovolta
nekovolta

Reputation: 516

Concatenate two arrays into a new array

I have two arrays,

A = np.array([[1,2,3],[4,5,6]])
b = np.array([100,101])

I want to concatenate them so that b is added a column on the right-hand side so we have a new array A | b that would be something like:

1 2 3 100

4 5 6 101

I am trying with concatenate this way:

new = np.concatenate((A, b), axis=1)

But I get the next error:

ValueError: all the input arrays must have the same number of dimensions, but the array at index 0 has 2 dimension(s), and the array at index 1 has 1 dimension(s)

How can I concatenate these two arrays?

Upvotes: 1

Views: 318

Answers (2)

GGranroth
GGranroth

Reputation: 11

You could also Transpose A do a vertical stack and then transpose it back np.vstack((A.T,b)).T

Upvotes: 1

Mustafa Aydın
Mustafa Aydın

Reputation: 18306

You can use column_stack:

>>> np.column_stack((A, b))

array([[  1,   2,   3, 100],
       [  4,   5,   6, 101]])

which takes care of b not being 2D.


To make concatenate work, we manually make b of shape (2, 1):

>>> np.concatenate((A, b[:, np.newaxis]), axis=1)

array([[  1,   2,   3, 100],
       [  4,   5,   6, 101]])

Upvotes: 2

Related Questions