Ka Wa Yip
Ka Wa Yip

Reputation: 2983

Add single element to array as first entry in numpy

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

Upvotes: 0

Views: 1128

Answers (3)

hpaulj
hpaulj

Reputation: 231325

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.

Upvotes: 1

Imanol Luengo
Imanol Luengo

Reputation: 15889

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

Upvotes: 0

Related Questions