Skip to content

Instantly share code, notes, and snippets.

@f-ewald
Created July 7, 2018 21:07
Show Gist options
  • Save f-ewald/9846d9d8b6fef11ff033391076834f30 to your computer and use it in GitHub Desktop.
Save f-ewald/9846d9d8b6fef11ff033391076834f30 to your computer and use it in GitHub Desktop.
Calculate mean value per row of sparse matrix
import numpy
from scipy.sparse import csr_matrix
A = numpy.array([[0, 0, 1],[0,2,4]])
# array([[0, 0, 1],
# [0, 2, 4]])
B = csr_matrix(A)
d = B.getnnz(axis=1) # Get number of non zero entries
print(d)
# array([1, 2], dtype=int32)
print(B.sum(axis=1).A.reshape(-1)/d)
# array([1., 3.])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment