user user - 2 months ago 11
Python Question

inserting values into numpy array

I am new to python and numpy, coming from a java background.

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'.

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

Answer

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

>>> a = np.empty(5,dtype = int)
>>> a
array([-2305843009213693952, -2305843009213693952,           4336320554,
                          0,                    0])
>>> k = np.empty(5,dtype = int)
>>> k
array([-2305843009213693952, -2305843009213693952,           4336320556,
                 4294967297,      140215654037360])

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 np.append() i.e.

>>> a = np.array([],dtype = int)
>>> a = np.append(a,2)
>>> a = np.append(a,1)
>>> a = np.append(a,3)
>>> a = np.append(a,5)
>>> a
array([2, 1, 3, 5])

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

>>> a = np.empty(3,dtype = np.int)
>>> a[0] = 2
>>> a[1] = 1
>>> a[2] = 5
>>> a = np.append(a,3)
>>> a
array([2, 1, 5, 3])
Comments