-2

I'm not sure how to explain why I want to do this but...why does this code

x = np.array([1,2,3,4])
d = np.empty((0, 4))
d = np.append(d,[x],axis=0)
x[0]=8
d = np.append(d,[x],axis=0)

give me this

array([[ 1.,  2.,  3.,  4.],
       [ 8.,  2.,  3.,  4.]])

while this code

x = np.array([1,2,3,4])
d = np.empty((0, 4))
d = np.append(d,[x],axis=0)
x = d[0,]
x[0]=8
d = np.append(d,[x],axis=0)

gives me this?

array([[ 8.,  2.,  3.,  4.],
       [ 8.,  2.,  3.,  4.]])

Thanks in advance for any help here!

Rubarb
  • 555

1 Answers1

1

The issue is not with append but rather the assignment (bindings) of numpy arrays as pointers to the same location in memory.

Consider the following example

import numpy as np
x = np.array([1, 2, 3, 4])
y = x
y[0] = 8
print(x)

One would expect that since one did not modify the array x, that the print statement would yield the output [1,2,3,4] but in fact the real output is [8,2,3,4]. The arrays x and y are indistinguishable because they are pointers and via the assignment y=x they point to the same address of memory.

I assume that in your example, pointers became shared with the command x=d[0,].

See https://ecco-v4-python-tutorial.readthedocs.io/ECCO_v4_Operating_on_Numpy_Arrays.html for a more thorough discussion.

Tucker
  • 2,090
  • 9
  • 12