索引与数组numpy的数组赋值操作 [英] Numpy arrays assignment operations indexed with arrays
问题描述
我有一个数组是
与价值观的指标是必须的一个的另一种阵列增加 X
就像 X [Y] + = 1
,这是一个例子:
>>> X = np.zeros(5,DTYPE = np.int)
>>> Y = np.array([1,4])
>>> X
阵列([0,0,0,0,0])
>>> X [Y] + = 1
>>> X
阵列([0,1,0,0,1])
到目前为止好,但我已经这样的问题:
>>> X
阵列([0,1,0,0,1])
>>> Y = np.array([1,1])
>>> X
阵列([0,1,0,0,1])
>>> X [Y] + = 1
>>> X
阵列([0,2,0,0,1])
我期待 X
是阵列([0,3,0,0,1])
: X [1]
应加一两次,
但我与明白了X [1]
只加一。
如何能做到呢?为什么会发生这种情况?
X [Y] + = 1
是相当于
X [Y] = X [Y] + 1
X [Y] +1
#阵列([2,2])
有效 numpy的
运行在平行的条款,不按顺序。
X [Y] = [4,3]#或
X [Y] + = [4,3]
表明,如果不同的值被分配到相同的术语,它是一个具有作用的最后一个动作(但可能不保证)。
np.add.at(X,Y,1)
做你所期望的。
从np.add.at的文档
:
有关加成ufunc,该方法等效于
A [指数] + = B
,但结果累积元素
被索引不止一次。例如,A [0,0] + = 1
只会
递增一次,因为缓冲的第一要素,而
add.at(A,[0,0],1)
将递增的第一个元素的两倍。
块引用>I have an array
y
with indexes of values that must be incremented by one in another arrayx
just likex[y] += 1
, This is an example:>>> x = np.zeros(5,dtype=np.int) >>> y = np.array([1,4]) >>> x array([0, 0, 0, 0, 0]) >>> x[y] += 1 >>> x array([0, 1, 0, 0, 1])
So far so good, but then I've this problem:
>>> x array([0, 1, 0, 0, 1]) >>> y = np.array([1,1]) >>> x array([0, 1, 0, 0, 1]) >>> x[y] += 1 >>> x array([0, 2, 0, 0, 1])
I was expecting
x
to bearray([0, 3, 0, 0, 1])
:x[1]
should be incremented by one twice, but I got it withx[1]
incremented just by one.How can I did it? Why is that happening?
解决方案x[y] += 1
is the equivalent to
x[y] = x[y] + 1 x[y]+1 # array([2, 2])
Effectively
numpy
operates on the terms in parallel, not sequentially.x[y]=[4,3] # or x[y] += [4,3]
suggests that if different values are assigned to the same term, it is the last action that one has effect (but that probably isn't guaranteed).
np.add.at(x,y,1)
does what you expect.
from the documentation for
np.add.at
:For addition ufunc, this method is equivalent to
a[indices] += b
, except that results are accumulated for elements that are indexed more than once. For example,a[[0,0]] += 1
will only increment the first element once because of buffering, whereasadd.at(a, [0,0], 1)
will increment the first element twice.
这篇关于索引与数组numpy的数组赋值操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!