Array modified by two others in python

Suppose we have three one-dimensional arrays:

  • A (say length 5)
  • B (same length, 5 in the example)
  • C (much longer, e.g. length 100)

C initially filled with zeros. A gives the indices of the elements of C that should be changed (they can be repeated), and B gives the values ​​to be added to the initial zeros of C For example, if A = [1, 3, 3, 3, 29] and B = [2, 3, 4, 2, 3] , C[1] should become 2, C[3] - 9 , C[29] - 3 ; all other C elements should remain 0. I wrote this as a for loop:

 for i in range(len(A) - 1): C[A[i]] = C[A[i]] + B[i] 

But is there a more efficient way to do the same in numpy in vector form?

+4
source share
1 answer

I think you could use bincount , at least for the 1-D case:

 >>> A = np.array([1,3,3,3,29]) >>> B = np.array([2,3,4,2,3]) >>> np.bincount(A, B) array([ 0., 2., 0., 9., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 3.]) 

(In addition, duplicate values ​​when using numpy indexing can behave very strange, and it’s very easy to get the behavior that you see in simple cases out of the way. I completely avoid them, since the behavior is almost never what I want.)

+3
source

Source: https://habr.com/ru/post/1499646/


All Articles