scipy.signal.convolve2d
seems to be perfect fit for this application.
color_matrix = grid_colors.reshape(50, 50)
from scipy import signal
adjacent_boxes = np.array([[1,1,1], [1,0,1], [1,1,1]])
red_dots = signal.convolve2d(color_matrix, adjacent_boxes, mode='same', boundary='fill')
blue_dots = signal.convolve2d(1 - color_matrix, adjacent_boxes, mode='same', boundary='fill')
red_dots
>>>
array([[1, 2, 2, ..., 0, 0, 0],
[0, 2, 4, ..., 0, 0, 0],
[1, 1, 2, ..., 1, 0, 0],
...,
[1, 2, 1, ..., 1, 1, 0],
[2, 3, 0, ..., 1, 1, 1],
[1, 2, 0, ..., 1, 0, 0]])
blue_dots
>>>
array([[2, 3, 3, ..., 5, 5, 3],
[5, 6, 4, ..., 8, 8, 5],
[4, 7, 6, ..., 7, 8, 5],
...,
[4, 6, 7, ..., 7, 7, 5],
[3, 5, 8, ..., 7, 7, 4],
[2, 3, 5, ..., 4, 5, 3]])
red_dots + blue_dots
>>>
array([[3, 5, 5, ..., 5, 5, 3],
[5, 8, 8, ..., 8, 8, 5],
[5, 8, 8, ..., 8, 8, 5],
...,
[5, 8, 8, ..., 8, 8, 5],
[5, 8, 8, ..., 8, 8, 5],
[3, 5, 5, ..., 5, 5, 3]])
To have it inside dataframe, (thanks to @patrick artner) you can use:
sample_data['red_dots'] = red_dots.flatten()
sample_data['blue_dots'] = blue_dots.flatten()
print(sample_data)
X Y grid_color red_dots blue_dots
0 1.0 1.0 0 1 2
1 2.0 1.0 0 2 3
2 3.0 1.0 1 2 3
... ... ... ... ... ...
2498 49.0 50.0 0 0 5
2499 50.0 50.0 0 0 3
[2500 rows x 5 columns]