How to check if 2-D array is in another 2-D array
<p>consider the two dataframes <code>df1</code> and <code>df2</code></p>

<pre><code>df1 = pd.DataFrame(np.zeros((6, 6)), list('abcdef'), list('abcdef'), dtype=int)
df1.iloc[2:4, 2:4] = np.array([[1, 2], [3, 4]])

df1
</code></pre>

<p><a href="http://i.stack.imgur.com/UEWbP.png" rel="nofollow"><img src="http://i.stack.imgur.com/UEWbP.png" alt="enter image description here"></a></p>

<pre><code>df2 = pd.DataFrame(np.array([[1, 2], [3, 4]]), list('CD'), list('CD'), dtype=int)

df2
</code></pre>

<p><a href="http://i.stack.imgur.com/dUPSc.png" rel="nofollow"><img src="http://i.stack.imgur.com/dUPSc.png" alt="enter image description here"></a></p>

<p>It's clear that <code>df2</code> is in <code>df1</code>.  How do I test for this in general?</p>

<p>Assuming the dataframes contain <code>0's</code> and <code>1s</code> only, you can use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.convolve2d.html" rel="nofollow"><code>2D convolution</code></a> and look if any element in the convoluted output is equal to the number of elements in <code>df2</code>  -</p>

<pre><code>from scipy.signal import convolve2d

out = (convolve2d(df1,df2)==df2.size).any()
</code></pre>

<hr>

<p>For a generic case, let me use <a href="http://scikit-image.org/docs/dev/api/skimage.html" rel="nofollow"><code>skimage</code> module</a> and <a href="http://stackoverflow.com/a/32531759/3293881"><code>this smart solution</code></a> -</p>

<pre><code>from skimage.util import view_as_windows as viewW

out = ((viewW(df1.values, df2.shape) == df2.values).all(axis=(2,3))).any()
</code></pre>

<p>This is basically a template-matching problem and it has been discussed and we have gotten really efficient solutions under this post : <a href="http://stackoverflow.com/questions/32531377/how-can-i-check-if-one-two-dimensional-numpy-array-contains-a-specific-pattern-o"><code>How can I check if one two-dimensional NumPy array contains a specific pattern of values inside it?</code></a>. That post also gives us the indices of all places in <code>df1</code> where <code>df2</code> could be located.</p>

python pandas numpy scipy