inserting values into numpy array
<p>I am new to python and numpy, coming from a java background.</p>

<p>I want to insert int values into a an array. 
However my current way of doing it is not resulting in the proper values. 
I create an array 'a' of size 5, and would like to insert int values into 'a'. </p>

<pre><code>data = ocr['data']
test_data = ocr['testdata']

a = np.empty(5, dtype=np.int)
for t in range(0,5):
   np.append(a,np.dot(np.subtract(test_data[t], data[0]), np.subtract(test_data[t], data[d])))
</code></pre>

<p>When you initialize a numpy array by <code>np.empty()</code>, it allocates enough space for you, but the values inside these supposedly empty cells will be random rubbish. E.g.</p>

<pre><code>&gt;&gt;&gt; a = np.empty(5,dtype = int)
&gt;&gt;&gt; a
array([-2305843009213693952, -2305843009213693952,           4336320554,
                          0,                    0])
&gt;&gt;&gt; k = np.empty(5,dtype = int)
&gt;&gt;&gt; k
array([-2305843009213693952, -2305843009213693952,           4336320556,
                 4294967297,      140215654037360])
</code></pre>

<p>Hence, you have two choices: initilize an empty array with length 0 then append. NOTE: as @hpaulj pointed out, you need to set some array to be equal to the array returned by <code>np.append()</code> i.e.</p>

<pre><code>&gt;&gt;&gt; a = np.array([],dtype = int)
&gt;&gt;&gt; a = np.append(a,2)
&gt;&gt;&gt; a = np.append(a,1)
&gt;&gt;&gt; a = np.append(a,3)
&gt;&gt;&gt; a = np.append(a,5)
&gt;&gt;&gt; a
array([2, 1, 3, 5])
</code></pre>

<p>Or you can initialize by <code>np.empty()</code> but then you have to use up all the cells that you initialized first before appending. i.e.</p>

<pre><code>&gt;&gt;&gt; a = np.empty(3,dtype = np.int)
&gt;&gt;&gt; a[0] = 2
&gt;&gt;&gt; a[1] = 1
&gt;&gt;&gt; a[2] = 5
&gt;&gt;&gt; a = np.append(a,3)
&gt;&gt;&gt; a
array([2, 1, 5, 3])
</code></pre>

python arrays numpy