title: Most efficient way to calculate the average of a function between pairs for each element in Python?
body: <p><strong>Problem:</strong></p>
  <ul>
  <li>I have M objects sampled at different frames and I want to calculate the distance between pairs at each frame. I store the distances as a multidimensional array <code>xij</code> with three axis, where the element <code>xij[t,i,j]</code> corresponds to the distance between the objects <code>i</code> and <code>j</code> at time <code>t</code>. For example, we could have:
  <pre class="lang-py prettyprint-override"><code>N  = 10**5
  M = 10
  xij = np.random.uniform(0, 10, N).reshape(int(N/M**2), M, M)
  </code></pre>
  </li>
  <li>Now I want to calculate <strong>for each element the average distance to other pairs</strong> (that is, <em>excluding pairs between the same objects</em> <code>xij[t,i,i]</code>). The way I implemented this was first changing the values of these indices to NaN and then using <code>np.nanmean()</code>:
  <pre class="lang-py prettyprint-override"><code>xij[...,np.arange(M), np.arange(M)] = np.nan
  mean = np.nanmean(xij, axis = -1) 
  </code></pre>
  </li>
  <li>However, changing all these values to <code>np.nan</code> becomes a bottleneck in my program and it seems to me that maybe is not necessary. <strong>Is there a faster alternative?</strong> I see there is an argument <code>where</code> in <code>np.mean</code> to choose the elements to include in the calculation as a boolen array. I wonder if you could create this array more efficiently than using the <code>Nan</code> trick I implemented. Or alternatively, maybe using masked arrays? Although I am not familiar with them.</li>
  </ul>