3

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])))
4
  • Are you trying to insert values in the middle of the array? At the beginning? Or append them to the end? Commented Sep 18, 2016 at 3:41
  • append it to the end Commented Sep 18, 2016 at 3:41
  • Np.append is just a form of np.concatenate. It returns a new array. Review its docs. Commented Sep 18, 2016 at 3:44
  • I think you want a[I]=n.dot...; that is assign a new value each preallocated element of a. Commented Sep 18, 2016 at 3:47

1 Answer 1

3

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])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.