title: Accessing the values of surrounding cells in a dataframe without using a loop
body: <p>I am looking for a way to calculate for each cell in a dataframe the sum of the values of all surrounding cells (including in diagonal), without using a loop.</p>
  
  <p>I have come up with something that looks like that, but it does not include diagonals, and as soon as I include diagonals some cells are counted too many times.</p>
  
  <pre><code># Initializing matrix a
  columns = [x for x in range(10)]
  rows = [x for x in range(10)]
  matrix = pd.DataFrame(index=rows, columns=columns).fillna(0)
  
  # filling up with mock values
  matrix.iloc[5,4] = 1
  matrix.iloc[5,5] = 1
  matrix.iloc[5,6] = 1
  matrix.iloc[4,5] = 1
  
  matrix1 = matrix.apply(lambda x: x.shift(1)).fillna(0)
  matrix2 = matrix.T.apply(lambda x: x.shift(1)).T.fillna(0)
  matrix3 = matrix.apply(lambda x: x.shift(-1)).fillna(0)
  matrix4 = matrix.T.apply(lambda x: x.shift(-1)).T.fillna(0)
  
  matrix_out = matrix1 + matrix2 + matrix3 + matrix4
  </code></pre>
  
  <p>To be more precise, I plan on populating the dataframe only with 0 or 1 values. The test above is the following:</p>
  
  <pre><code>   0  1  2  3  4  5  6  7  8  9
  0  0  0  0  0  0  0  0  0  0  0
  1  0  0  0  0  0  0  0  0  0  0
  2  0  0  0  0  0  0  0  0  0  0
  3  0  0  0  0  0  0  0  0  0  0
  4  0  0  0  0  0  1  0  0  0  0
  5  0  0  0  0  1  1  1  1  0  0
  6  0  0  0  0  0  0  0  0  0  0
  7  0  0  0  0  0  0  0  0  0  0
  8  0  0  0  0  0  0  0  0  0  0
  9  0  0  0  0  0  0  0  0  0  0
  </code></pre>
  
  <p>The expected output for this input is:</p>
  
  <pre><code>   0  1  2  3  4  5  6  7  8  9
  0  0  0  0  0  0  0  0  0  0  0
  1  0  0  0  0  0  0  0  0  0  0
  2  0  0  0  0  0  0  0  0  0  0
  3  0  0  0  0  1  1  1  0  0  0
  4  0  0  0  1  3  3  4  2  1  0
  5  0  0  0  1  2  3  3  1  1  0
  6  0  0  0  1  3  3  3  2  1  0
  7  0  0  0  0  0  0  0  0  0  0
  8  0  0  0  0  0  0  0  0  0  0
  9  0  0  0  0  0  0  0  0  0  0
  </code></pre>
  
  <p>Am I in the right direction with this shift() function used within apply, or would you suggest doing otherwise?</p>
  
  <p>Thanks a lot!</p>