3

I'm trying to replace a sub array in a Numpy array, with an array of the same shape, such that any changes are mirrored in both arrays. I've run the following code in IDLE.

import numpy
a=numpy.zeros((2,1))

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

b=numpy.zeros((1))
b
array([0.])

a[0]=b
b[0]=1

b
array([1.])

Now what I'd want the output of a to be in this example is:

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

but instead I get:

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

I've been trying to read up on slicing and indexing, but it's not immediately obvious to me what I'm doing wrong here, or if it's even possible to get the result I want. So I was hoping someone could tell me how, if at all, I can do this.

1
  • a[0]=b assigns the value of b to a, but not the object. If a was a list it would work, but not with numeric arrays. Commented Apr 6, 2020 at 13:04

1 Answer 1

1

You can initialize b as being a slice of a, then changing b will modify a aswell, namely:

import numpy as np

a=np.zeros((2,1))
b=a[0]
b[0]=1

a
array([[1.],
       [0.]])

Hope this helps.

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.