Reputation: 93
I have a NumPy array
import numpy as np
A = np.array([2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
I want to insert a new column to A
to make it look like
A=[[1,2], [1,3], [1,4], [1,5], [1,6], [1,7], [1,8], [1,9], [1,10], [1,11]]
I tried using NumPy.insert(A,0,1,axis=1)
but it gives following error:
AxisError: axis 1 is out of bounds for array of dimension 1
I can't find where I am doing wrong. Please help me rectify this and suggest any other method(s).
Upvotes: 0
Views: 499
Reputation: 231335
The column_stack
or array
that others suggest are fine, but to stick with the insert
:
In [126]: A = np.array([2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
In [127]: A.shape
Out[127]: (10,)
In [128]: A[:,None].shape
Out[128]: (10, 1)
In [129]: np.insert(A[:,None],0,1, axis=1)
Out[129]:
array([[ 1, 2],
[ 1, 3],
[ 1, 4],
[ 1, 5],
[ 1, 6],
[ 1, 7],
[ 1, 8],
[ 1, 9],
[ 1, 10],
[ 1, 11]])
To do an insert on axis 1, A
has to have such an axis, i.e. has to be 2d. That's what your error message was all about. A
is only 1d.
Upvotes: 1
Reputation: 827
np.insert insert only single value, you need to stack a second column. you can use np.column_stack or np.c_
import numpy as np
A=np.array([2,3,4,5,6,7,8,9,10,11])
arr1 = np.ones(len(A))
out = np.c_[arr1,A]
array([[ 1., 2.],
[ 1., 3.],
[ 1., 4.],
[ 1., 5.],
[ 1., 6.],
[ 1., 7.],
[ 1., 8.],
[ 1., 9.],
[ 1., 10.],
[ 1., 11.]])
np.column_stack((arr1,A))
array([[ 1., 2.],
[ 1., 3.],
[ 1., 4.],
[ 1., 5.],
[ 1., 6.],
[ 1., 7.],
[ 1., 8.],
[ 1., 9.],
[ 1., 10.],
[ 1., 11.]])
Upvotes: 1
Reputation: 482
Perhaps this is what you want:
a = np.array([1,2,3,4,5,6,7,8,9,10,11])
b = np.ones(a.shape[0])
c = np.array((b,a)).T
Output is:
[[ 1. 1.]
[ 1. 2.]
[ 1. 3.]
[ 1. 4.]
[ 1. 5.]
[ 1. 6.]
[ 1. 7.]
[ 1. 8.]
[ 1. 9.]
[ 1. 10.]
[ 1. 11.]]
Upvotes: 0