8

I am trying to append to a numpy array using np.append.

For example,

a = np.array([1])

np.append(a, [2])

this code works well in terminal (the result is array([1, 2])), but it won't work when I run a .py file including the same code included in it. When I print a after appending [2], it would still be [1].

Here is the code for my test.py file:

import numpy as np

a = np.array([1])
print(a)
np.append(a, [2])
print(a)

and this is the result of running it with terminal:

python test.py
[1]
[1]

Wrong result with no error. Does anyone know what could possibly be the problem?

user3052069
  • 323
  • 1
  • 3
  • 12

3 Answers3

13
import numpy as np
a = np.array([1])
print(a)
a = np.append(a, [2])
print(a)

numpy.append(arr, values, axis=None), where arr is values are appended to a copy of this array (http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.append.html).

In terminal your code works because np.append(a,[2]) become print np.append(a,[2]).

Serenity
  • 35,289
  • 20
  • 120
  • 115
2

Are you sure that the version of numpy used within your terminal and for the execution of your .py file the same? According to http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.append.html np.append in numpy 1.10.0 is not in place and is therefore consistent with the behaviour you are getting from python test.py

To compare the versions, you can print and compare numpy.__version__

bantmen
  • 748
  • 6
  • 17
  • 1
    According to an answer of [this question](http://stackoverflow.com/questions/34597871/numpy-wont-append-arrays) , I found out that it was because I wasn't using a 'copy' of the array. In the terminal, using np.append() directly yields the result, whereas in the .py file np.append() function seems to throw away(?) the result before printing the value of a. This is how I fixed my code in test.py, and it works now: `import numpy as np a = np.array([1]) print(a) a = np.append(a, [2]) print(a)` – user3052069 May 29 '16 at 08:13
  • `np.append` is another way of using `np.concatenate`. It is not, and never was, a clone of list append. – hpaulj May 29 '16 at 11:39
1

You're misunderstanding what the terminal is doing. When you write the following in a terminal:

>>> a = np.array([1])
>>> np.append(a, [2])
array([1, 2])

You obviously didn't ask it to print, but it does. So the terminal must have inserted a print statement. The terminal is actually running:

a = np.array([1])
print repr(np.append(a, [2]))

That is, all expressions that do not return None are wrapped in print repr(...)

Of course your code is not inserting the same print statement, so of course it gives a different result

Eric
  • 95,302
  • 53
  • 242
  • 374