Numpy花哨的索引和赋值 [英] Numpy fancy indexing and assignment

查看:449
本文介绍了Numpy花哨的索引和赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常numpy强制分配的左侧和右侧匹配,例如,如果我 a [:] = b b 必须与 a 具有相同的形状或广播形式。但该规则似乎有例外:

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. 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])

它似乎只适用于1d数组,并且只有在赋值的左侧有花哨的索引,但我无法在任何地方找到此行为的文档。是否记录了这种行为,如果有的话,还有人可以举例说明它何时有用?

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. Is this behavior documented, if so where, and also can someone give an example of when it might be useful?

更新:

似乎numpy flatiter类型的行为也是这样,flatiter和fancy indexing之间是否存在一些我不知道的关联?

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?

>>> 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])


推荐答案

我认为这种行为是以R及其祖先S / S-plus为模型的。这就是列表赋值(向量赋值)在那里工作的方式,它被称为回收。 R项目网站谈到了它,但我在此链接上找到了更有启发性的解释。在R中,矢量是测量的集合,因此以它的方式填充或修剪它是有意义的。这种逻辑有多少让它变得笨拙,为什么,这仍然是一个很好的问题。

I think this behavior is modeled on R and its ancestor 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. In R, a vector is a collection of measurements, so it makes sense to pad or trim it the way it does. How much of this logic has made it to numpy, and why, is still a good question.

这篇关于Numpy花哨的索引和赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆