简体   繁体   English

Numpy花哨索引和分配

[英]Numpy fancy indexing and assignment

Normally numpy forces the left and right side of an assignment to match, so for example if I do a[:] = b , b must be the same shape or broadcast to the same shape as a . 通常numpy的力的分配的左侧和右侧,以匹配,因此,例如,如果我做a[:] = bb必须是相同的形状或广播到相同的形状a But there seems to be an exception to that rule: 但该规则似乎有例外:

>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = a.copy()
>>> a[[0,1,2]] = b[::2]
>>> a
array([0, 2, 4, 3, 4, 5, 6, 7, 8, 9])
>>> a[np.arange(10)] = b[:2]
>>> a
array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1])

It seems to only work with 1d arrays and only if there is fancy indexing on the left side of the assignment, but I haven't been able to find documentation for this behavior anywhere. 它似乎只适用于1d数组,并且只有在赋值的左侧有花哨的索引,但我无法在任何地方找到此行为的文档。 Is this behavior documented, if so where, and also can someone give an example of when it might be useful? 是否记录了这种行为,如果有的话,还有人可以举例说明它何时有用?

Update: 更新:

It seems that the numpy flatiter type behaves this way too, is there some connection between flatiter and fancy indexing that I don't know about? 看起来numpy flatiter类型的行为也是这样,flatiter和fancy indexing之间是否存在一些我不知道的联系?

>>> a.flat = [10,11]
>>> a
array([10, 11, 10, 11, 10, 11, 10, 11, 10, 11])
>>> a.flat[:] = [2,3,4]
>>> a
array([2, 3, 4, 2, 3, 4, 2, 3, 4, 2])
>>> a.flat = range(100)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

I think this behavior is modeled on R and its ancestor S/S-plus. 我认为这种行为是以R及其祖先S / S-plus为蓝本的。 That's how list assignment ("vector" assignment) works there, and it's called "recycling". 这就是列表赋值(“向量”赋值)在那里的工作方式,它被称为“回收”。 The R project website talks about it, but I found a more illuminating explanation at this link . R项目网站谈到了它,但我在这个链接上找到了更有启发性的解释。 In R, a vector is a collection of measurements, so it makes sense to pad or trim it the way it does. 在R中,矢量是测量的集合,因此以它的方式填充或修剪它是有意义的。 How much of this logic has made it to numpy, and why, is still a good question. 这种逻辑有多少让它变得笨拙,为什么,这仍然是个好问题。

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

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