Reputation: 3202
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?
Upvotes: 2
Views: 396
Reputation: 107287
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.]])
Upvotes: 0
Reputation: 3324
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]])
Upvotes: 2
Reputation: 18446
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]]
Upvotes: 2