Replacing sub array in Numpy array

Viewed 59

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 Answers

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.

Related