Comparing by section two numpy arrays in python
<p>I want to do a comparison between the two arrays by section.
so far I have to get results for all arrays.</p>

<pre><code>import numpy as np
array1 = np.array(list(np.zeros(20))+(list(np.ones(20)))+(list(2*np.ones(20))))
array2 = np.array(list(np.ones(20))+(list(np.ones(20)))+(list(3*np.ones(20))))
result = np.sum(array1 == array2)
print 'all result :' + str(result)
</code></pre>

<p>how to can result in parts, such as the first data 20 then 20 the second data and 20 third data in the array??
the result should be:</p>

<p>all result : 20</p>

<p>result for 20 firt data : 0</p>

<p>result for 20 second data : 20</p>

<p>result for 20 third data : 0</p>

<p>First off, let's get the mask of comparisons -</p>

<pre><code>mask = array1 == array2
</code></pre>

<p>Then, to get all sum -</p>

<pre><code>allsum = mask.sum()
</code></pre>

<p>And to get sectionwise (of length <code>20</code>) sum -</p>

<pre><code>section_sums = mask.reshape(-1,20).sum(1)
</code></pre>

<p>Sample run -</p>

<pre><code>In [77]: mask = array1 == array2

In [78]: mask.sum()
Out[78]: 20

In [79]: mask.reshape(-1,20).sum(1)
Out[79]: array([ 0, 20,  0])
</code></pre>

<hr>

<p><strong>For generic lengths</strong></p>

<p>If the length of input arrays are not guaranteed to be a multiple of <code>20</code>, we could use an approach using <code>np.bincount</code> to get <code>section_sums</code>, like so -</p>

<pre><code>section_sums = np.bincount(np.arange(mask.size)//20,mask)
</code></pre>

<p>Sample run -</p>

<pre><code>In [5]: a1=np.array(list(np.zeros(20))+(list(np.ones(20)))+(list(2*np.ones(17))))
   ...: a2=np.array(list(np.ones(20))+(list(np.ones(20)))+(list(3*np.ones(17))))
   ...: 

In [6]: mask = a1==a2

In [7]: np.bincount(np.arange(mask.size)//20,mask)
Out[7]: array([  0.,  20.,   0.])
</code></pre>

python arrays python-2.7 numpy