18

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!

Trung Tran
  • 11,579
  • 39
  • 105
  • 187
  • Close, but you have only two axis (axis 0 = 569 and axis 1 = 30), try `axis=1`. – umutto Oct 12 '17 at 01:45
  • hi - that was a typo.. i just updated my question with my array's shapes and the error i get back – Trung Tran Oct 12 '17 at 01:48
  • 2
    Ahh your `array_2` only has one dimension, needs to have same number of dimensions with your `array_1`. You can either reshape it `array_2.reshape(-1,1)`, or add a new axis `array_2[:,np.newaxis]` to make it 2 dimensional before concatenation. – umutto Oct 12 '17 at 01:53

3 Answers3

27

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]])
Psidom
  • 195,464
  • 25
  • 298
  • 322
0

To stack them vertically try

np.vstack((array1,array2))
buddemat
  • 3,262
  • 10
  • 15
  • 39
-1

You can simply use numpy's hstack function.

e.g.

import numpy as np

combined = np.hstack((array1,array2))
Maximouse
  • 3,550
  • 1
  • 13
  • 25