This is a typical problem where you can use numpy.bincount. For this, I used three functions:
(x,y,z)=scipy.sparse.find(a)
returns rows ( x ), columns ( y ), and values ββ( z ) of a sparse matrix. For instace x there is array([0, 1, 1, 1].
numpy.bincount(x) returns for each line number the number of unnecessary unnecessary elements.
numpy.bincount(x,wights=z) returns for each row the sum of nonzero elements.
Final working code:
from scipy.sparse import csr_matrix a = csr_matrix([[0, 0, 2], [1, 3, 8]]) import numpy import scipy.sparse (x,y,z)=scipy.sparse.find(a) countings=numpy.bincount(x) sums=numpy.bincount(x,weights=z) averages=sums/countings print(averages)
returns:
[ 2. 4.]
source share