Reputation: 1485
I am trying to simply add a column of ones to a numpy array but cannot find any easy solution to what I feel should be a straightforward answer. The number of rows in my array may change therefore the solution needs to generalise.
import numpy as np
X = np.array([[1,45,23,56,34,23],
[2,46,24,57,35,23]])
My desired output:
array([[ 1, 45, 23, 56, 34, 23, 1],
[ 2, 46, 24, 57, 35, 23, 1]])
I have tried using np.append
and np.insert
, but they either flatten the array or replace the values.
Thanks.
Upvotes: 2
Views: 6228
Reputation: 36450
You might use numpy.insert following way:
import numpy as np
X = np.array([[1,45,23,56,34,23], [2,46,24,57,35,23]])
X1 = np.insert(X, X.shape[1], 1, axis=1)
print(X1)
Output:
[[ 1 45 23 56 34 23 1]
[ 2 46 24 57 35 23 1]]
Upvotes: 1
Reputation: 15349
You can use append
, but you have to tell it which axis
you want it to work along:
np.append(X, [[1],[1]], axis=1)
Upvotes: 0
Reputation: 150745
you can do hstack
:
np.hstack((X,np.ones([X.shape[0],1], X.dtype)))
Output:
array([[ 1, 45, 23, 56, 34, 23, 1],
[ 2, 46, 24, 57, 35, 23, 1]])
Upvotes: 4