# [SciPy-user] Sparse csr_matrix and column sum

Nathan Bell wnbell@gmail....
Sun Apr 27 19:08:23 CDT 2008

```On Sun, Apr 27, 2008 at 6:41 PM, Dinesh B Vadhia
>
>
> If A is a sparse csr_matrix and you want to calculate the sum of each column
> then the 'normal' method is:
>
> import numpy
> import scipy
> from scipy import sparse
>
> colSum = scipy.asmatrix(scipy.zeros((1,J), dtype=numpy.float))
> colSum = A.mean(0)
>
> This isn't working.  Do we have to do something else (eg. a todense()) for a
> sparse matrix?  If so, how?

What do you mean by "isn't working"?

In [1]: from scipy import *
In [2]: from scipy.sparse import *
In [3]: A = csr_matrix(rand(3,3))
In [4]: A.todense()
Out[4]:
matrix([[ 0.95297535,  0.81029421,  0.79146232],
[ 0.88477059,  0.9025494 ,  0.80259054],
[ 0.06691343,  0.76691617,  0.68518027]])
In [5]: A.mean(0)
Out[5]: matrix([[ 0.63488646,  0.82658659,  0.75974438]])
In [6]: A.mean(1)
Out[6]:
matrix([[ 0.85157729],
[ 0.86330351],
[ 0.50633662]])
In [7]: A.todense().mean(0)
Out[7]: matrix([[ 0.63488646,  0.82658659,  0.75974438]])
In [8]: A.todense().mean(1)
Out[8]:
matrix([[ 0.85157729],
[ 0.86330351],
[ 0.50633662]])

Dinesh, as a courtesy, would you provide specific details when
reporting your problems with SciPy?  I'd rather not have to speculate
on the precise nature of each issue raised.

--
Nathan Bell wnbell@gmail.com
http://graphics.cs.uiuc.edu/~wnbell/
```