2

This seem to be a trivial question, yet I did not find the answer I am looking for. I have a 2D array say:

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

And another column

b = np.array([9,11])
bt = np.reshape(b, (2,1))

I would like to add/append the bt column at the zero column of array a. I tried using numpy.insert:

tt = np.insert(a,0,bt,axis=1)

But the result is:

array([[ 9, 11,  1,  3,  5],
       [ 9, 11,  2,  4,  6]])

What I want is:

array([[ 9, 1,  3,  5],
       [ 11,  2,  4,  6]])

What am I doing wrong?

3 Answers 3

2

You can use numpy.column_stack to do that:

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

array([[ 9,  1,  3,  5],
       [11,  2,  4,  6]])
Sign up to request clarification or add additional context in comments.

Comments

2

You can either directly use b:

tt = np.insert(a, 0, b, axis=1)
print tt

[[ 9  1  3  5]
 [11  2  4  6]]

Or, if you are starting with something shaped like bt, transpose it:

tt = np.insert(a, 0, bt.T, axis=1)
print tt

[[ 9  1  3  5]
 [11  2  4  6]]

Comments

0

As an alternative alongside np.hstack you can play with indexing :

>>> c=np.zeros((a.shape[0],a.shape[1]+1))
>>> c[::,0]=b
>>> c[::,1:]=a
>>> c
array([[  9.,   1.,   3.,   5.],
       [ 11.,   2.,   4.,   6.]])

2 Comments

This is an interesting solution. But I am not fully following. What are: >>>c[::,0]=b >>> c[::,1:]=a
@Arcticpython its column assignment ! c[::,0]=b will assign b on the firs column of c and c[::,1:]=a will assign the a on the second column of c to end

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.