Adam
Adam

Reputation: 169

insert element in the start of the numpy array

I have array

x=[ 0.30153836  0.30376881  0.29115761  0.29074261  0.28676876 ]

I want to insert -1 to the start of the array to be like

  x= [-1 0.30153836  0.30376881  0.29115761  0.29074261  0.28676876]

I tried :

np.insert(x,0,-1,axis=0)

but it didn't do any change, any idea how to do that ?

Upvotes: 2

Views: 5397

Answers (3)

hpaulj
hpaulj

Reputation: 231665

From the np.insert documentation:

Returns
out : ndarray
   A copy of `arr` with `values` inserted.  Note that `insert`
   does not occur in-place: a new array is returned. 

You can do the same with concatenate, joining the new value to the main value. hstack, append etc use concatenate; insert is more general, allowing insertion in the middle (for any axis), so it does its own indexing and new array creation.

In any case, the key point is that it does not operate in-place. You can't change the size of an array.

In [788]: x= np.array([0.30153836,  0.30376881,  0.29115761,  0.29074261,  0.28
     ...: 676876])
In [789]: y=np.insert(x,0,-1,axis=0)
In [790]: y
Out[790]: 
array([-1.        ,  0.30153836,  0.30376881,  0.29115761,  0.29074261,
        0.28676876])
In [791]: x
Out[791]: array([ 0.30153836,  0.30376881,  0.29115761,  0.29074261,  0.28676876])

Same action with concatenate; note that I had to add [], short for np.array([-1]), so both inputs are 1d arrays. Expanding the scalar to array is all that insert is doing special.

In [793]: np.concatenate([[-1],x])
Out[793]: 
array([-1.        ,  0.30153836,  0.30376881,  0.29115761,  0.29074261,
    0.28676876])

Upvotes: 3

Billy
Billy

Reputation: 5609

I'm not fully familiar with numpy, but it seems that the insert function does not affect the array you pass to it, but rather it returns a new array with the inserted value(s). You'll have to reassign to x if you really want x to change.

>>> x= [-1, 0.30153836,  0.30376881,  0.29115761,  0.29074261,  0.28676876]
>>> np.insert(x,0,-1,axis=0)
array([-1.        , -1.        ,  0.30153836,  0.30376881,  0.29115761,
        0.29074261,  0.28676876])
>>> x
[-1, 0.30153836, 0.30376881, 0.29115761, 0.29074261, 0.28676876]
>>> x = np.insert(x,0,-1,axis=0)
>>> x
array([-1.        , -1.        ,  0.30153836,  0.30376881,  0.29115761,
        0.29074261,  0.28676876])

Upvotes: 2

Simon
Simon

Reputation: 10160

You can do the insert by ommiting the axis param:

x = np.array([0,0,0,0])
x = np.insert(x, 0, -1)
x

That will give:

array([-1,  0,  0,  0,  0])

Upvotes: 3

Related Questions