3

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

4 Answers 4

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]]
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.