title: Most efficient way to find neighbors of neighbors in python
body: <p>Let's consider, there are two arrays <code>I</code> and <code>J</code> which determine the neighbor pairs:</p>
  <pre><code>I = np.array([0, 0, 1, 2, 2, 3])
  J = np.array([1, 2, 0, 0, 3, 2])
  </code></pre>
  <p>Which means element <code>0</code> has two neighbors <code>1</code> and <code>2</code>. Element <code>1</code> has only <code>0</code> as a neighbor and so on.</p>
  <p>What is the most efficient way to create arrays of all neighbor triples <code>I'</code>, <code>J'</code>, <code>K'</code> such that <code>j</code> is neighbor of <code>i</code> and <code>k</code> is neighbor of <code>j</code> given the condition <code>i</code>, <code>j</code>, and <code>k</code> are different elements (<code>i != j != k</code>)?</p>
  <pre><code>Ip = np.array([0, 0, 2, 3])
  Jp = np.array([2, 2, 0, 2])
  Kp = np.array([0, 3, 1, 0])
  </code></pre>
  <p>Of course, one way is to loop over each element. Is there a more efficient algorithm? (working with 10-500 million elements)</p>