2

I've been thinking about this for a while now, and I just can't make sense of what is going on here.. hopefully it's something simple? In the output below I would expect a '41' in the first element of the second entry of 'c'.

>>> a = np.zeros(shape = (2,2))
>>> b = np.zeros(shape = (2,2))
>>> c = [np.array(x) for x in range(3)]
>>> c[1] = np.zeros(shape=(2,2,3))
>>> c[1][:,:,0] = a.view()
>>> a
array([[ 0.,  0.],
       [ 0.,  0.]])
>>> c
[array(0), array([[[ 0.,  0.,  0.],
                   [ 0.,  0.,  0.]],

                  [[ 0.,  0.,  0.],
                   [ 0.,  0.,  0.]]]), array(2)]
>>> a[0,0] = 41
>>> a
array([[ 41.,   0.],
       [  0.,   0.]])
>>> c
[array(0), array([[[ 0.,  0.,  0.],
                   [ 0.,  0.,  0.]],

                  [[ 0.,  0.,  0.],
                   [ 0.,  0.,  0.]]]), array(2)]

1 Answer 1

3

Because you did:

c[1][:,:] = a.view()

Which makes a shallow copy.

If you did c[1] = a.view() instead you would see the behaviour you expected.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, that makes sense because it's creating a slice right? (which is a copy).. soo, this situation is actually something more like this (updated the question), so I can't just do the direct indexing on 'c'..
I think wim is still right. What you are doing is assigning a.view() to a slice of the array c[1], modifying that array in-place. This copies the values from a.view() into c[1]. It's not possible to make a slice of one array act as a view into another array. numpy doesn't support this at all.

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.