gpt4 book ai didi

python - 为什么原始 numpy 数组在更新其副本后也会更新?

转载 作者:太空宇宙 更新时间:2023-11-03 16:48:24 26 4
gpt4 key购买 nike

我对意外的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com