This question already has answers here:
numpy array assignment problem
                                
                                    (2个答案)
                                
                        
                                3年前关闭。
            
                    
我一直对Python的意外行为感到困惑:当我复制原始的numpy数组并将其某些元素替换为不同的值时,原始数组的相应元素也会被更新。这是一个简单的测试:

>>import numpy as np
>>x = np.array([0,0,2,2])
>>x_adj = x
>>x_adj[x_adj <= 0] = 1
>>print x
>>print x_adj
  [1 1 2 2]
  [1 1 2 2]


我想知道为什么还要更新原始数组,以及如何保持其完整,以便仅对副本进行更改。欢迎任何反馈!

最佳答案

分配不是numpy中对象的副本。您只需要处理对对象的引用,即可复制实际的数组用途

x_adj = x.copy()


您可以通过id功能轻松检查它

>>> import numpy as np
>>> x = np.array([0])
>>> print id(x)
140686120123168
>>> x_adj = x
>>> print id(x_adj)
140686120123168
>>> print id(x.copy())
140685864181632

关于python - 为什么原始numpy数组在更新其副本后会得到更新? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36106826/

10-11 22:59
查看更多