Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing sub array in Numpy array

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.

like image 321
groscadituqoi Avatar asked Aug 31 '26 19:08

groscadituqoi


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.

like image 123
FBruzzesi Avatar answered Sep 02 '26 10:09

FBruzzesi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!