2

How can I add a column containing only "1" to the beginning of a second numpy array.

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

I want to have X become

[[1,1,2], [1,3,4],[1,5,6]]
Nakx
  • 1,460
  • 1
  • 23
  • 32
Moose
  • 67
  • 1
  • 6
  • Does this answer your question? [How to add an extra column to a NumPy array](https://stackoverflow.com/questions/8486294/how-to-add-an-extra-column-to-a-numpy-array) – Green Dec 01 '19 at 11:31

4 Answers4

2
  • You can use the np.insert

    new_x = np.insert(x, 0, 1, axis=1)
    
  • You can use the np.append method to add your array at the right of a column of 1 values

    x = np.array([[1, 2], [3, 4], [5, 6]])
    ones = np.array([[1]] * len(x))
    new_x = np.append(ones, x, axis=1)
    

Both will give you the expected result

[[1 1 2]
 [1 3 4]
 [1 5 6]]
azro
  • 53,056
  • 7
  • 34
  • 70
1

Try this:

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

>>> np.insert(X, 0, 1, axis=1)
array([[1, 1, 2],
       [1, 3, 4],
       [1, 5, 6]])
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
0

Since a new array is going to be created in any event, it is just sometimes easier to do so from the beginning. Since you want a column of 1's at the beginning, then you can use builtin functions and the input arrays existing structure and dtype.

a = np.arange(6).reshape(3,2)               # input array
z = np.ones((a.shape[0], 3), dtype=a.dtype) # use the row shape and your desired columns
z[:, 1:] = a                                # place the old array into the new array
z
array([[1, 0, 1],
       [1, 2, 3],
       [1, 4, 5]])
NaN
  • 2,212
  • 2
  • 18
  • 23
0

numpy.insert() will do the trick.

X = np.array([[1, 2], [3, 4], [5, 6]])
np.insert(X,0,[1,2,3],axis=1)

The Output will be:

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

Note that the second argument is the index before which you want to insert. And the axis = 1 indicates that you want to insert as a column without flattening the array.

For reference: numpy.insert()