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>Here is one way using <code>np.split()</code>:</p>

<pre><code>In [36]: np.array(np.split(c, np.arange(2, c.shape[1], 2), axis=1)).sum(axis=-1)
Out[36]: 
array([[ 0.  ,  0.5 ,  0.5 ],
       [ 0.75,  0.25,  0.  ]])
</code></pre>

<p>Or as a more general way even for odd length arrays:</p>

<pre><code>In [87]: def vertical_adder(array):
             return np.column_stack([np.sum(arr, axis=1) for arr in np.array_split(array, np.arange(2, array.shape[1], 2), axis=1)])
   ....: 

In [88]: vertical_adder(c)
Out[88]: 
array([[ 0.  ,  0.75],
       [ 0.5 ,  0.25],
       [ 0.5 ,  0.  ]])

In [94]: a
Out[94]: 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

In [95]: vertical_adder(a)
Out[95]: 
array([[ 1,  5,  4],
       [11, 15,  9],
       [21, 25, 14]])
</code></pre>

python numpy