Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

python - A numpy array unexpectedly changes when changing another one despite being separate

I found a bug in my large code, and I simplified the issue to the case below.

Although in each step I only change w2, but when at each step I print out w1, it is also changed, because end of the first loop I assign them to be equal. I read for this but there was written in case I make w1 = w2[:] it will solve the issue but it does not

import numpy as np
import math

w1=np.array([[1,2,3],[4,5,6],[7,8,9]])
w2=np.zeros_like(w1)
print 'w1=',w1
for n in range(0,3):
    for i in range(0,3):
        for j in range(0,3):
            print 'n=',n,'i=',i,'j=',j,'w1=',w1
            w2[i,j]=w1[i,j]*2

    w1=w2[:]


#Simple tests
# w=w2[:]
# w1=w[:]

# p=[1,2,3]
# q=p[:];
# q[1]=0;
# print p
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue is that when you're assigning values back to w1 from w2 you aren't actually passing the values from w1 to w2, but rather you are actually pointing the two variables at the same object.

The issue you are having

w1 = np.array([1,2,3])
w2 = w1

w2[0] = 3

print(w2)   # [3 2 3]
print(w1)   # [3 2 3]

np.may_share_memory(w2, w1)  # True

The Solution

Instead you will want to copy over the values. There are two common ways of doing this with numpy arrays.

w1 = numpy.copy(w2)
w1[:] = w2[:]

Demonstration

w1 = np.array([1,2,3])
w2 = np.zeros_like(w1)

w2[:] = w1[:]

w2[0] = 3

print(w2)   # [3 2 3]
print(w1)   # [1 2 3]

np.may_share_memory(w2, w1)   # False

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...