I am writing a program in python and I want to vectorize it as much as possible. I have the following variables
- 2D array of zeros
E
with shape(L,T)
. - array
w
with shape(N,)
with arbitrary values. - array
index
with shape(A,)
whose values are integers between0
andN-1
. The values are unique. - array
labels
with a shape the same asw
((A,)
), whose values are integers between0
andL-1
. The values are not necessarily unique. - Integer
t
between0
andT-1
.
We want to add the values of w
at indices index
to the array E
at rows labels
and column t
. I used the following code:
E[labels,t] += w[index]
But this approach does not give desired results. For example,
import numpy as np
E = np.zeros([10,1])
w = np.arange(0,100)
index = np.array([1,3,4,12,80])
labels = np.array([0,0,5,5,2])
t = 0
E[labels,t] += w[index]
Gives
array([[ 3.],
[ 0.],
[80.],
[ 0.],
[ 0.],
[12.],
[ 0.],
[ 0.],
[ 0.],
[ 0.]])
But the correct answer would be
array([[ 4.],
[ 0.],
[80.],
[ 0.],
[ 0.],
[16.],
[ 0.],
[ 0.],
[ 0.],
[ 0.]])
Is there a way to achieve this behavior without using a for loop?
I realized I can use this: np.add.at(E,[labels,t],w[index])
but it gives me this warning:
FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.