Addition of every two columns
<p>I would like calculate the sum of two in two column in a matrix(the sum between the columns 0 and 1, between 2 and 3...).</p>

<p>So I tried to do nested "for" loops but at every time I haven't the good results.</p>

<p>For example:</p>

<pre><code>c = np.array([[0,0,0.25,0.5],[0,0.5,0.25,0],[0.5,0,0,0]],float)
freq=np.zeros(6,float).reshape((3, 2))

#I calculate the sum between the first and second column, and between the fird and the fourth column
for i in range(0,4,2):
    for j in range(1,4,2):
        for p in range(0,2):
            freq[:,p]=(c[:,i]+c[:,j])
</code></pre>

<p>But the result is:</p>

<pre><code> print freq           
 array([[ 0.75,  0.75],
        [ 0.25,  0.25],
        [ 0.  ,  0.  ]])
</code></pre>

<p>Normaly the good result must be (0., 0.5,0.5) and (0.75,0.25,0). So I think the problem is in the nested "for" loops.</p>

<p>Is there a person who know how I can calculate the sum every two columns, because I have a matrix with 400 columns?</p>

<p>You can simply reshape to split the last dimension into two dimensions, with the last dimension of length <code>2</code> and then sum along it, like so -</p>

<pre><code>freq = c.reshape(c.shape[0],-1,2).sum(2).T
</code></pre>

<p>Reshaping only creates a view into the array, so effectively, we are just using the summing operation here and as such must be efficient.</p>

<p>Sample run -</p>

<pre><code>In [17]: c
Out[17]: 
array([[ 0.  ,  0.  ,  0.25,  0.5 ],
       [ 0.  ,  0.5 ,  0.25,  0.  ],
       [ 0.5 ,  0.  ,  0.  ,  0.  ]])

In [18]: c.reshape(c.shape[0],-1,2).sum(2).T
Out[18]: 
array([[ 0.  ,  0.5 ,  0.5 ],
       [ 0.75,  0.25,  0.  ]])
</code></pre>

python numpy