Note that there are some explanatory texts on larger screens.

plurals
  1. POProduct of array elements by group in numpy (Python)
    primarykey
    data
    text
    <p>I'm trying to build a function that returns the products of subsets of array elements. Basically I want to build a <code>prod_by_group</code> function that does this:</p> <pre><code>values = np.array([1, 2, 3, 4, 5, 6]) groups = np.array([1, 1, 1, 2, 3, 3]) Vprods = prod_by_group(values, groups) </code></pre> <p>And the resulting <code>Vprods</code> should be:</p> <pre><code>Vprods array([6, 4, 30]) </code></pre> <p>There's a great answer here for sums of elements that I think it should be similar to: <a href="https://stackoverflow.com/a/4387453/1085691">https://stackoverflow.com/a/4387453/1085691</a></p> <p>I tried taking the <code>log</code> first, then <code>sum_by_group</code>, then <code>exp</code>, but ran into numerical issues.</p> <p>There are some other similar answers here for min and max of elements by group: <a href="https://stackoverflow.com/a/8623168/1085691">https://stackoverflow.com/a/8623168/1085691</a></p> <p>Edit: Thanks for the quick answers! I'm trying them out. I should add that I want it to be as fast as possible (that's the reason I'm trying to get it in numpy in some vectorized way, like the examples I gave).</p> <p>Edit: I evaluated all the answers given so far, and the best one is given by @seberg below. Here's the full function that I ended up using:</p> <pre><code>def prod_by_group(values, groups): order = np.argsort(groups) groups = groups[order] values = values[order] group_changes = np.concatenate(([0], np.where(groups[:-1] != groups[1:])[0] + 1)) return np.multiply.reduceat(values, group_changes) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload