尽管分开,但在更改另一个数组时,numpy 数组意外更改 [英] 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.
虽然在每一步我只改变了w2
,但是当我在每一步打印出w1
时,它也被改变了,因为我在第一个循环结束时分配了它们平等.我读了这个,但写了以防万一我让 w1 = w2[:]
它会解决问题,但它不会
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
推荐答案
问题在于,当您将值从 w2
分配回 w1
时,您不是实际上将值从 w1
传递到 w2
,而是您实际上将两个变量指向同一个对象.
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.
您遇到的问题
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
解决方案
相反,您需要复制值.使用 numpy 数组有两种常用方法.
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[:]
演示
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
这篇关于尽管分开,但在更改另一个数组时,numpy 数组意外更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!