简体   繁体   English

numpy切片和索引不同的结果

[英]numpy slicing and indexing different results

In numpy subarrays obtained through any of slicing, masking or fancy indexing operations are just views to the original array, which can be demonstrated as follows: 在通过任何切片,掩蔽或花式索引操作获得的numpy子数组中,只是对原始数组的视图,可以如下所示:

$ python3
Python 3.5.2 (default, Nov 23 2017, 16:37:01) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> np.__version__
'1.11.0'

>>> a = np.arange(3); a[:2] = 111; a
array([111, 111,   2])

>>> a = np.arange(3); a[a<2] = 111; a
array([111, 111,   2])

>>> a = np.arange(3); a[[0,1]] = 111; a
array([111, 111,   2])

In the above example, the entire subarray was assigned to. 在上面的例子中,整个子阵列被分配给。 However if we assign to an element of the subarray, the result of the slicing operation still behaves as a view, whereas the results of the masking and fancy indexing operations behave as independent copies: 但是,如果我们分配给子数组的一个元素,则切片操作的结果仍然表现为视图,而屏蔽和花式索引操作的结果表现为独立副本:

>>> a = np.arange(3); a[:2][0] = 111; a
array([111,   1,   2])

>>> a = np.arange(3); a[a<2][0] = 111; a
array([0, 1, 2])

>>> a = np.arange(3); a[[0,1]][0] = 111; a
array([0, 1, 2])

Is this a bug in numpy, or is it by design? 这是一个numpy的错误,还是设计? If it is by design, then what's the substantiation for such an inconsistency? 如果是设计,那么这种不一致的证据是什么?

It's not a bug. 这不是一个错误。 As far as you pass a slice object to Numpy array the returned sub array is a view of the original items which means that even slice assignment or single item assignments will change the original array. 只要将切片对象传递给Numpy数组,返回的子数组就是原始项的视图,这意味着即使切片分配或单项分配也会更改原始数组。 But in other cases the returned result is not a view. 但在其他情况下,返回的结果不是视图。 It's, in fact, a shallow view (copy) of the chosen slice which only supports slice assignment like what other mutable objects in Python support. 实际上,它是所选切片的浅视图(副本),它仅支持切片分配,就像Python支持的其他可变对象一样。

It's also mentioned in documentation : 文档中也提到了它:

[...] As with index arrays, what is returned is a copy of the data, not a view as one gets with slices. [...]与索引数组一样,返回的是数据的副本,而不是切片所获得的视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM