scipy.sparse matrix: subtract row mean to nonzero elements
<p>I have a sparse matrix in <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.sparse.csr_matrix.html" rel="nofollow">csr_matrix</a> format. For each row i need to subtract row mean from the nonzero elements. The means must be computed on the number of the nonzero elements of the row (instead of the length of the row).
I found a fast way to compute the row means with the following code:</p>

<pre><code># M is a csr_matrix
sums = np.squeeze(np.asarray(M.sum(1)))    # sum of the nonzero elements, for each row
counts = np.diff(M.tocsr().indptr)         # count of the nonzero elements, for each row


# for the i-th row the mean is just sums[i] / float(counts[i]) 
</code></pre>

<p>The problem is the updates part. I need a fast way to do this.
Actually what i am doing is to transform M to a <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.lil_matrix.html" rel="nofollow">lil_matrix</a> and perform the updates in this way:</p>

<pre><code>M = M.tolil()

for i in xrange(len(sums)):
    for j in M.getrow(i).nonzero()[1]:
        M[i, j] -= sums[i] / float(counts[i])
</code></pre>

<p>which is slow. Any suggestion for a faster solution?</p>

<p>This one is tricky. I think I have it. The basic idea is that we try to get a diagonal matrix with the means on the diagonal, and a matrix that is like M, but has ones at the nonzero data locations in M. Then we multiply those and subtract the product from M. Here goes...   </p>

<pre><code>&gt;&gt;&gt; import numpy as np
&gt;&gt;&gt; import scipy.sparse as sp
&gt;&gt;&gt; a = sp.csr_matrix([[1., 0., 2.], [1.,2.,3.]])
&gt;&gt;&gt; a.todense()
matrix([[ 1.,  0.,  2.],
        [ 1.,  2.,  3.]])
&gt;&gt;&gt; tot = np.array(a.sum(axis=1).squeeze())[0]
&gt;&gt;&gt; tot
array([ 3.,  6.])
&gt;&gt;&gt; cts = np.diff(a.indptr)
&gt;&gt;&gt; cts
array([2, 3], dtype=int32)
&gt;&gt;&gt; mu = tot/cts
&gt;&gt;&gt; mu
array([ 1.5,  2. ])
&gt;&gt;&gt; d = sp.diags(mu, 0)
&gt;&gt;&gt; d.todense()
matrix([[ 1.5,  0. ],
        [ 0. ,  2. ]])
&gt;&gt;&gt; b = a.copy()
&gt;&gt;&gt; b.data = np.ones_like(b.data)
&gt;&gt;&gt; b.todense()
matrix([[ 1.,  0.,  1.],
        [ 1.,  1.,  1.]])
&gt;&gt;&gt; (d * b).todense()
matrix([[ 1.5,  0. ,  1.5],
        [ 2. ,  2. ,  2. ]])
&gt;&gt;&gt; (a - d*b).todense()
matrix([[-0.5,  0. ,  0.5],
        [-1. ,  0. ,  1. ]])
</code></pre>

<p>Good Luck! Hope that helps.</p>

python scipy updates sparse-matrix mean