insert element in the start of the numpy array
<p>I have array </p>

<pre><code>x=[ 0.30153836  0.30376881  0.29115761  0.29074261  0.28676876 ]
</code></pre>

<p>I want to insert -1 to the start of the array to be like </p>

<pre><code>  x= [-1 0.30153836  0.30376881  0.29115761  0.29074261  0.28676876]
</code></pre>

<p>I tried :</p>

<pre><code>np.insert(x,0,-1,axis=0)
</code></pre>

<p>but it didn't do any change, any idea how to do that ?</p>

<p>From the <code>np.insert</code> documentation:</p>

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

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

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

<pre><code>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])
</code></pre>

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

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

python arrays numpy