简体   繁体   English

使用带有冗余元素的python数组索引python数组

[英]Indexing python array with a python array with redundant elements

I'm experiencing a problem with array indexing. 我遇到了数组索引的问题。 Suppose you have an array a and another array b you want to use to use as index for a in order to assign some values to the position pointed by b elements. 假设您有一个数组a和另一个要用作a的索引的数组b,以便为b元素指向的位置分配一些值。

a=numpy.zeros(5)
print a

[ 0.  0.  0.  0.  0.]

Now I would like to increase the second element twice 现在我想两次增加第二个元素

b=numpy.array([1,1])
a[b]+=1.
print a

[ 0.  1.  0.  0.  0.]

while I expected to have 虽然我期望有

[ 0.  2.  0.  0.  0.] 

There are no problems if the array b has no redundancies (all values of its elements are different). 如果阵列b没有冗余(其元素的所有值都不同),则没有问题。 Has somebody got a solution for such a problem which avoids using for loops? 有人为这样的问题找到了解决方案,避免使用for循环吗? Is it a bug in numpy? 这是一个numpy的错误吗? Thanks in advance 提前致谢

When you use an integer array for indexing another array, NumPy cannot create an adequate view, since the resulting array may not be representable with strides. 当您使用整数数组索引另一个数组时,NumPy无法创建足够的视图,因为生成的数组可能无法用步幅表示。 Therefore, it will return a copy: 因此,它将返回一份副本:

>>> a = np.zeros(5)
>>> b = np.array([1, 1])
>>> c = a[b]
>>> c
array([ 0.,  0.])
>>> c.base is a
False

When using this index with in-place operations like += , NumPy will interpret it differently than you expect. 将此索引与+=等就地操作一起使用时,NumPy会以不同的方式对其进行解释。 Instead of "Walk the index array and perform the operation on each element in turn", it will first select all values that are indexed by b (in this case, just one element with index 1 ), then perform the operation on these elements once . 而不是“遍历索引数组并依次对每个元素执行操作”,它将首先选择由b索引的所有值(在这种情况下,只是一个索引为1元素),然后对这些元素执行一次操作

or you can use bincount(): 或者您可以使用bincount():

a=numpy.zeros(5)
idx = numpy.bincount([0,0,0,1,1,3,3])
a[:len(idx)]+=idx

You can try: 你可以试试:

a += numpy.histogram(b, numpy.arange(len(a)+1))[0]

This will return a = array([ 0., 2., 0., 0., 0.]) 这将返回a = array([ 0., 2., 0., 0., 0.])

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

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