numpy中的数组切片 [英] array slicing in numpy
问题描述
今天,我使用numpy数组进行了一些计算,发现了一个奇怪的问题,例如,假定我已经在Ipython中导入了numpy.arange,并且我按如下方式运行了一些脚本:
today I used the numpy array for some calculation and found a strange problem, for example, assume i already imported numpy.arange in Ipython, and I run some scripts as follows:
In [5]: foo = arange(10)
In [8]: foo1 = foo[arange(3)]
In [11]: foo1[:] = 0
In [12]: foo
Out[12]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [16]: foo2 = foo[0:3]
In [19]: foo2[:]=0
In [21]: foo
Out[21]: array([0, 0, 0, 3, 4, 5, 6, 7, 8, 9])
上图显示,当我用foo [arange(3)]分割数组时,我得到了数组切片的副本,但是当我用foo [0:3]分割数组时,我得到了数组的引用切片,因此foo随foo2一起变化.然后我认为foo和foo2应该具有相同的id,但这似乎是不正确的
above shows that when i slice the array by foo[arange(3)], i got a copy of the array slice, but when i slice the array by foo[0:3], i got a reference of the array slice, thus foo changes with foo2. Then I thought foo and foo2 should have the same id, but that seems is not true
In [59]: id(foo)
Out[59]: 27502608
In [60]: id(foo2)
Out[60]: 28866880
In [61]: id(foo[0])
Out[61]: 38796768
In [62]: id(foo2[0])
Out[62]: 38813248
...
甚至更奇怪的是,如果我继续检查foo和foo2的ID,它们不是恒定的,有时它们确实是相互匹配的!
even more strange, if I keep checking the id of foo and foo2, they are not constant, and sometimes, they did match each other!
In [65]: id(foo2[0])
Out[65]: 38928592
In [66]: id(foo[0])
Out[66]: 37111504
In [67]: id(foo[0])
Out[67]: 38928592
有人可以解释一下吗?我真的对python的动态功能感到困惑
can anyone explain this a little bit? I am really confused by this dynamic feature of python
非常感谢
推荐答案
foo[arange(3)]
不是切片. arange(3)
的元素用于选择 foo
的元素以构造一个新数组.由于这不能有效地返回视图(视图的每个元素都必须是一个独立的引用,并且对该视图的操作将需要遵循太多的指针),因此它返回一个新数组.
is not a slice. The elements of arange(3)
are used to select elements of foo
to construct a new array. Since this can't efficiently return a view (every element of the view would have to be an independent reference, and operations on the view would require following far too many pointers), it returns a new array.
foo[0:3]
是一片.可以有效地做到这一点.它只需要调整一些界限.因此,它返回一个视图.
is a slice. This can be done efficiently as a view; it only requires adjusting some bounds. Thus, it returns a view.
id(foo[0])
foo [0]
没有引用特定的Python对象.为每个数组元素保留单独的Python对象将非常昂贵,从而抵消了numpy的许多好处.相反,当对numpy ndarray执行索引操作时,numpy构造一个新对象以返回.每次都会得到一个具有不同ID的不同对象.
foo[0]
doesn't refer to a specific Python object. Keeping separate Python objects for every array element would be far too expensive, negating much of the benefit of numpy. Instead, when an indexing operation is performed on a numpy ndarray, numpy constructs a new object to return. You'll get a different object with a different ID every time.
这篇关于numpy中的数组切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!