Marambo - 3 months ago 13

Python Question

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...).

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

For example:

`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])

But the result is:

`print freq`

array([[ 0.75, 0.75],

[ 0.25, 0.25],

[ 0. , 0. ]])

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.

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

Answer

Here is one way using `np.split()`

:

```
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. ]])
```

Or as a more general way even for odd length arrays:

```
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]])
```