Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a column to a numpy array

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]]
like image 491
Moose Avatar asked Jun 07 '26 00:06

Moose


2 Answers

  • 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]]
like image 147
azro Avatar answered Jun 08 '26 14:06

azro


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]])
like image 22
Arkistarvh Kltzuonstev Avatar answered Jun 08 '26 12:06

Arkistarvh Kltzuonstev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!