我正在尝试将一个简单的布尔掩码应用于 np 数组。下面是一个简单的例子。
temp = np.arange(5)
print(temp)
temp1 = temp
temp1[temp1 < 2] = 0
print(temp1)
print(temp)
Run Code Online (Sandbox Code Playgroud)
我已经将 temp 的值分配给了一个新变量 temp1,所以我期望掩码仅适用于变量 temp1。但是,temp 的值也会更新。我想知道为什么会发生这种情况。
结果:
[0 1 2 3 4]
[0 0 2 3 4]
[0 0 2 3 4]
Run Code Online (Sandbox Code Playgroud)
你的变量temp1和temp引用同一个对象。使用.copy()这样就不会改变原来的以获得该项目的浅表副本。
temp = np.arange(5)
print(temp)
temp1 = temp.copy()
temp1[temp1 < 2] = 0
print(temp1)
print(temp)
Run Code Online (Sandbox Code Playgroud)
如果您想了解有关名称和引用的更多信息,请访问 https://nedbatchelder.com/text/names.html/
| 归档时间: |
|
| 查看次数: |
531 次 |
| 最近记录: |