Calculate mean of array with specific value from another array
<p>I have these numpy arrays:</p>

<pre><code>array1 = np.array([-1, -1, 1, 1, 2, 1, 2, 2])
array2 = np.array([34.2, 11.2, 22.1, 78.2, 55.0, 66.87, 33.3, 11.56])
</code></pre>

<p>Now I want to return a 2d array in which there is the mean for each distinctive value from array1 so my output would look something like this:</p>

<pre><code>array([[-1, 22.7],
       [ 1, 55.7],
       [ 2, 33.3]])
</code></pre>

<p>Is there an efficient way without concatenating those 1D arrays to one 2D array? Thanks!</p>

<p>This is a typical grouping operation, and the <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package (disclaimer: I am its author) provides extensions to numpy to perform these type of operations efficiently and concisely:</p>

<pre><code>import numpy_indexed as npi
groups, means = npi.group_by(array_1).mean(array_2)
</code></pre>

<p>Note that you can in this manner easily perform other kind of reductions as well, such as a median for example.</p>

python arrays performance numpy