0

How to achieve this? I have a numpy array containing:

[1, 2, 3]

I want to create an array containing:

[8, 1, 2, 3]

That is, I want to add an element on as the first element of the array.

Ref:Add single element to array in numpy

3 Answers 3

1

The most basic operation is concatenate:

x=np.array([1,2,3])
np.concatenate([[8],x])
# array([8, 1, 2, 3])

np.r_ and np.insert make use of this. Even if they are more convenient to remember, or use in more complex cases, you should be familiar with concatenate.

Sign up to request clarification or add additional context in comments.

Comments

1

Use numpy.insert(). The docs are here: http://docs.scipy.org/doc/numpy/reference/generated/numpy.insert.html#numpy.insert

Comments

0

You can also use numpy's np.r_, a short-cut for concatenation along the first axis:

>>> import numpy as np
>>> a = np.array([1, 2, 3])
>>> b = np.r_[8, a]
>>> b
array([8, 1, 2, 3])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.