5

I have a numpy array:

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

Now I want to add a column of all ones in front of it to get:

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

I saw many posts pertaining to my question, but none of them could solve my problem. I tried np.concatenate np.append np.hstack but unfortunately none of them worked.

3 Answers 3

8

Simply use np.concatenate:

>>> import numpy as np
>>> arr = np.array([[1, 2, 3],
                    [4, 5, 6],
                    [7, 8, 9]])

>>> np.concatenate((np.array([0,0,0])[:, np.newaxis], arr), axis=1)
array([[0, 1, 2, 3],
       [0, 4, 5, 6],
       [0, 7, 8, 9]])

But hstack works too:

>>> np.hstack((np.array([0,0,0])[:, np.newaxis], arr))
array([[0, 1, 2, 3],
       [0, 4, 5, 6],
       [0, 7, 8, 9]])

The only "tricky" part is that both arrays must have the same number of dimensions, that's why I added the [:, np.newaxis] - which adds a new dimension.

How to change the zeros to ones is left as an (easy) exercise :-)

If you want to prepend a 2D array you have to drop the [:, np.newaxis] part:

np.concatenate((np.zeros((3,3), dtype=int), arr), axis=1)
array([[0, 0, 0, 1, 2, 3],
       [0, 0, 0, 4, 5, 6],
       [0, 0, 0, 7, 8, 9]])
Sign up to request clarification or add additional context in comments.

5 Comments

Another nice way of including an extra dimension in situations like this is by indexing with None: np.array([0,0,0])[:, None]
@kiliantics np.newaxis is just an alias for None, see for example None is np.newaxis = True. But I think it's a bit more explicit and thus preferrable when answering questions for people learning numpy. But nevertheless thank you for the comment, it might help future visitors +1
@MSeifert, your solution worked fine. But when I try to generalize it gives me an error: np.concatenate((np.ones((3, 3))[:, np.newaxis], arr), axis=1) give me the error: ValueError: all the input arrays must have same number of dimensions
@BishwajitPurkaystha If you want to prepend a 2D array then just drop the [:, np.newaxis] part.
It would be better if you edit your answer for generalization for future reference. Thanks.
3

I prefer this way:

ones = np.ones((3,1)) #3 is a number of rows in your array.   
new_array = np.hstack((ones,arr))

Comments

1

vstack behaves a bit more nicely without having to worry about new axes, though MSeifert's answer is probably more correct:

p = np.array([1,1,1])
q = np.array([[1,2,3],[4,5,6],[7,8,9]])

np.vstack((p,q.T)).T

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.