Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

236
Visualizações
Add values in numpy array successively, without looping

Maybe has been asked before, but I can't find it. Sometimes I have an index I, and I want to add successively accordingly to this index to an numpy array, from another array. For example:

A = np.array([1,2,3])
B = np.array([10,20,30])
I = np.array([0,1,1])
for i in range(len(I)):
    A[I[i]] += B[i]
print(A)

prints the expected (correct) value:

[11 52  3]

while

A[I] += B
print(A)

results in the expected (wrong) answer

[11 32  3].

Is there any way to do what I want in a vectorized way, without the loop? If not, which is the fastest way to do this?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Use numpy.add.at:

>>> import numpy as np
>>> A = np.array([1,2,3])
>>> B = np.array([10,20,30])
>>> I = np.array([0,1,1])
>>> 
>>> np.add.at(A, I, B)
>>> A
array([11, 52,  3])

Alternatively, np.bincount:

>>> A = np.array([1,2,3])
>>> B = np.array([10,20,30])
>>> I = np.array([0,1,1])
>>> 
>>> A += np.bincount(I, B, minlength=A.size).astype(int)
>>> A
array([11, 52,  3])

Which is faster?

Depends. In this concrete example add.at seems marginally faster, presumably because we need to convert types in the bincount solution.

If OTOH A and B were float dtype then bincount would be faster.

over 4 years ago · Santiago Trujillo Relatório

0

You need to use np.add.at:

A = np.array([1,2,3])
B = np.array([10,20,30])
I = np.array([0,1,1])

np.add.at(A, I, B)
print(A)

prints

array([11, 52, 3])

This is noted in the doc:

ufunc.at(a, indices, b=None)

Performs unbuffered in place operation on operand ‘a’ for elements specified by ‘indices’. 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, whereas add.at(a, [0,0], 1) will increment the first element twice.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda