title: Python, neighbors on a regular grid
body: <p>Let's suppose I have a set of 2D coordinates that represent the centers of cells of a 2D regular mesh. I would like to find, for each cell in the grid, the two closest neighbors in each direction.</p>
  
  <p>The problem is quite straightforward if one assigns to each cell and index defined as follows:</p>
  
  <p>idx_cell = idx+N*idy</p>
  
  <p>where N is the total number of cells in the grid, idx=x/dx and idy=y/dx, with x and y being the x-coordinate and the y-coordinate of a cell and dx its size.</p>
  
  <p>For example, the neighboring cells for a cell with idx_cell=5 are the cells with idx_cell equal to 4,6 (for the x-axis) and 5+N,5-N (for the y-axis).</p>
  
  <p>The problem that I have is that my implementation of the algorithm is quite slow for large (N>1e6) data sets.</p>
  
  <p>For instance, to get the neighbors of the x-axis I do</p>
  
  <p><code>[x[(idx_cell==idx_cell[i]-1)|(idx_cell==idx_cell[i]+1)] for i in cells]</code></p>
  
  <p>Do you think there's a fastest way to implement this algorithm?</p>