-2

I have an 2D array :

1 2 3 4 5 6
2 6 5 2 4 1
8 7 9 0 0 0
2 3 4 5 6 2

How can I add a new column of 1D array to the above array?

1
0
1
0

So that the result will look like this?

1 2 3 4 5 6 1
2 6 5 2 4 1 0
8 7 9 0 0 0 1
2 3 4 5 6 2 0
  • EDIT: I'm not adding a column of zeros here.
PSN
  • 2,326
  • 3
  • 27
  • 52
  • I have tried but that ain't my question. He wants to add a column of zeros so the answer is np.zeros. My question is different. – PSN Jan 03 '18 at 14:36
  • The accepted answer suggests creating array of zeros then copy over the values, you can do the same, copy over the 2d array and then the 1d array – yosukesabai Jan 03 '18 at 14:42
  • @nicola Try np.concatenate((a,b.reshape(b.shape[0],1)),axis=1) This worked well – PSN Jan 03 '18 at 14:55

4 Answers4

3
np.concatenate((a,b.reshape(b.shape[0],1)),axis=1)

Solved the problem

PSN
  • 2,326
  • 3
  • 27
  • 52
1

Try this using hstack. vstack concatenate vertically and hstack concatenate horizontally

>>> a=np.arange(0,24)
>>> a=a.reshape((4,6))
>>> a
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23]])
>>> b=np.ones((4,1))
>>> c=np.hstack((a,b))
>>> c
array([[  0.,   1.,   2.,   3.,   4.,   5.,   1.],
       [  6.,   7.,   8.,   9.,  10.,  11.,   1.],
       [ 12.,  13.,  14.,  15.,  16.,  17.,   1.],
       [ 18.,  19.,  20.,  21.,  22.,  23.,   1.]])
>>> 
Artier
  • 1,648
  • 2
  • 8
  • 22
0

append method in numpy will do the job

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

c=np.append(a,b, axis=1)
print(c)

It gives output as follows:

[[1 2 3 5]
 [3 4 5 6]]
Sociopath
  • 13,068
  • 19
  • 47
  • 75
0

One can also try np.insert

x = np.array([[1, 2, 3, 4, 5, 6],
              [2, 6, 5, 2, 4, 1],
              [8, 7, 9, 0, 0, 0],
              [2, 3, 4, 5, 6, 2]])
y = np.array([1, 0, 1, 0])
# inserting at the 6th column can be achieved with this
np.insert(x, 6, y, axis=1)

array([[1, 2, 3, 4, 5, 6, 1],
       [2, 6, 5, 2, 4, 1, 0],
       [8, 7, 9, 0, 0, 0, 1],
       [2, 3, 4, 5, 6, 2, 0]])
Tai
  • 7,684
  • 3
  • 29
  • 49