Appproach # 1: It seems we are counting the number of occurrences of B in separate blocks. So we can use skimage.util.view_as_blocks -
from skimage.util import view_as_blocks as viewW out = np.count_nonzero((viewW(A, B.shape) == B).all((2,3)))
Appproach # 2: Staying with NumPy , we would have -
m1,n1 = A.shape m2,n2 = B.shape out = np.count_nonzero((A.reshape(m1
Run Examples -
In [274]: A Out[274]: array([[2, 0, 2, 0], [5, 3, 5, 1], [3, 3, 2, 6], [1, 0, 3, 1]]) In [275]: B Out[275]: array([[3, 3], [1, 0]]) In [276]: np.count_nonzero((viewW(A, B.shape) == B).all((2,3))) Out[276]: 1 In [278]: A Out[278]: array([[2, 0, 3, 3], [5, 3, 1, 0], [3, 3, 2, 6], [1, 0, 3, 1]]) In [279]: B Out[279]: array([[3, 3], [1, 0]]) In [280]: np.count_nonzero((viewW(A, B.shape) == B).all((2,3))) Out[280]: 2