简体   繁体   中英

Adding column of ones to numpy array

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.

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

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)  

You can use numpy.c_

np.c_[X, [1, 1]]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM