[英]Python: Applying a mask without changing the value to the original array
I am trying to apply a simple boolean mask to a np array. 我试图将一个简单的布尔掩码应用于np数组。 Following is an easy example.
以下是一个简单的示例。
temp = np.arange(5)
print(temp)
temp1 = temp
temp1[temp1 < 2] = 0
print(temp1)
print(temp)
I have already assign the value of temp to a new variable temp1, so what I expected is that the mask only applies on the variable temp1. 我已经将temp的值分配给新变量temp1,所以我期望的是掩码仅适用于变量temp1。 However, the value of temp is also updated.
但是,temp的值也会更新。 I wonder why is this happening.
我不知道为什么会这样。
Result: 结果:
[0 1 2 3 4]
[0 0 2 3 4]
[0 0 2 3 4]
Your variables temp1
and temp
refer to the same object. 您的变量
temp1
和temp
指向同一对象。 Use .copy()
to get a shallow copy of the item so it will not modify the original. 使用
.copy()
获取该项目的浅表副本,以便它不会修改原始项目。
temp = np.arange(5)
print(temp)
temp1 = temp.copy()
temp1[temp1 < 2] = 0
print(temp1)
print(temp)
If you want to learn more about names and referencing, https://nedbatchelder.com/text/names.html/ 如果要了解有关名称和引用的更多信息, 请https://nedbatchelder.com/text/names.html/
As was stated before, you're only getting a new reference to temp
. 如前所述,您只会获得对
temp
的新引用。 What that means is that although the variables are named differently, they both point to the same piece of memory. 这意味着尽管变量的名称不同,但是它们都指向同一块内存。 So, by changing the value in one, you actually change the value in both.
因此,通过更改一个中的值,实际上可以更改两个中的值。 To avoid this, you need to use, at the very least, a shallow copy.
为了避免这种情况,至少需要使用浅表副本。 Here's two ways to do this using numpy:
这是使用numpy做到这一点的两种方法:
temp1 = numpy.copy(temp)
or 要么
temp1 = np.array(temp, copy = True)
As others have noted, you need to explicitly ask for a copy when you're dealing with collection-like objects in python. 正如其他人指出的那样,在使用python处理类似集合的对象时,您需要显式地请求副本 。 The same behavior you're seeing here can happen with lists and dictionaries as well.
您在此处看到的相同行为也可能发生在列表和字典上。 Numpy has the nice helper method numpy.copy() that should solve your problems.
Numpy有很好的帮助程序方法numpy.copy(),它可以解决您的问题。
# one way
temp1 = temp.copy()
#another way
temp1 = numpy.copy(temp)
To add something that I thought might be useful, you can save the mask itself and then apply it by multiplying. 要添加我认为可能有用的内容,可以保存遮罩本身,然后通过乘以应用。
mask = temp < 2
masked_temp = temp * mask
This is useful in case you want to visualize or reuse this mask and makes the copy problem from before irrelevant (as masked_temp is not a copy, but a newly calculated array). 如果您想可视化或重复使用此掩码,并使之前的复制问题不相关(因为masked_temp不是副本,而是新计算的数组),这将很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.