Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

simple but difficult numpy memory reference problem

import numpy as np

a = np.array([0,0,0,0,0,0,0,0])
b = np.array([4,2,3])
c = np.array([5,5,2])

for i, e in enumerate(c):
    a[e] += b[i]
print(a)
# [0 0 3 0 0 6 0 0]

a = np.array([0,0,0,0,0,0,0,0])
b = np.array([4,2,3])
c = np.array([5,5,2])

a[c] += b[np.arange(len(b))]
print(a)
# [0 0 3 0 0 2 0 0]

The actual length of c is incredibly long. The problem comes from here.

The python for loop is too slow.

So I want to replace this with numpy without python for loop, but I can’t find a way.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I think it’s because of the memory reference.
Is there a way to change the result value of this to the same?

>Solution :

You can try np.add.at:

cnt = np.arange(0, len(c))
np.add.at(a, c, b[cnt])

print(a)

Prints:

[0 0 3 0 0 6 0 0]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading