关于NumPy数组切片何时是引用以及何时是副本的困惑 [英] Confusion about when NumPy array slices are references and when they are copies
问题描述
我有以下代码:
import numpy as np
arr = np.arange(10)
slice = arr[2:5]
slice[:] = 12
print(arr)
slice = slice / 2
print(arr)
输出将是:
[ 0 1 12 12 12 5 6 7 8 9]
[6. 6. 6.]
[ 0 1 12 12 12 5 6 7 8 9]
因此,围绕 slice
的第一次只是对 arr
的一部分的引用,因此对其进行修改也将更改数组,但是第二次围绕它已成为的副本.数组的该部分并对其进行修改在 arr
中没有区别.为什么会这样?是什么使 slice = slice/2
与众不同?
So the first time around slice
is just a reference to part of arr
so modifying it also changes the array, but the second time around it has become a copy of that part of the array and modifying it makes no difference in arr
. Why does this happen? What makes slice = slice / 2
different?
推荐答案
使用切片对象建立索引始终会返回数组的视图(引用).修改切片将修改原始数组.在第二个示例中,您将其分配给slice对象.那不会修改对象.将使用指定的值(在本例中为slice/2)创建一个新对象.如果这是所需的行为,则可以使用/=
在适当的位置修改该对象,或者在切片中建立索引([:]
),numpy解释为修改这些索引处的条目.
Indexing with a slice object always returns a view (reference) of an array. Modifying the slice will modify the original array. In your second example you assign to the slice object. That does not modify the object. A new object is created with the specified values, in this case slice / 2. You can use /=
to modify the object in place if that's the desired behavior, or index into the slice ([:]
) which numpy interprets as modifying the entries at those indices.
这篇关于关于NumPy数组切片何时是引用以及何时是副本的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!