Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python numpy array append not working in .py file, but works in terminal

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?

like image 973
user3052069 Avatar asked Dec 25 '22 05:12

user3052069


2 Answers

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

like image 82
Serenity Avatar answered Dec 26 '22 20:12

Serenity


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__

like image 29
bantmen Avatar answered Dec 26 '22 18:12

bantmen