Numpy efficient indexing with varied size arrays
<p>Take a look at this piece of code:</p>

<pre><code>import numpy as np

a = np.random.random(10)

indicies = [
    np.array([1, 4, 3]),
    np.array([2, 5, 8, 7, 3]),
    np.array([1, 2]),
    np.array([3, 2, 1])
]

result = np.zeros(2)
result[0] = a[indicies[0]].sum()
result[1] = a[indicies[2]].sum()
</code></pre>

<p>Is there any way to get <code>result</code> more efficiently? In my case <code>a</code> is a very large array.</p>

<p>In other words I want to select elements from <code>a</code> with several varying size index arrays and then sum over them in one operation, resulting in a single array.</p>

<p>If your array <strong>a</strong> is very large you might have <strong>memory issues</strong> if your array of indices contains many arrays of many indices when looping through it.</p>

<p>To avoid this issue use an iterator instead of a list :</p>

<pre><code>indices = iter(indices)
</code></pre>

<p>and then loop through your iterator.</p>

python arrays numpy