-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.
3
  • 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. Commented Jan 3, 2018 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 Commented Jan 3, 2018 at 14:42
  • @nicola Try np.concatenate((a,b.reshape(b.shape[0],1)),axis=1) This worked well Commented Jan 3, 2018 at 14:55

4 Answers 4

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

Solved the problem

Sign up to request clarification or add additional context in comments.

Comments

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.]])
>>> 

Comments

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]]

6 Comments

No unfortunately its not.
ValueError: all the input arrays must have same number of dimensions This is what I'm getting.
I added few more steps to the solution
Yea I tried that
Did it work? It's working for me atleast. Just check if you have passed 2D array in a new variable(variable b in my case)
|
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]])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.