You can directly change the data attribute:
>>> a = np.array([[5,0,0,0,0,0,0],[0,0,0,0,2,0,0]]) >>> coo = coo_matrix(a) >>> coo.data array([5, 2]) >>> coo.data = np.log(coo.data) >>> coo.data array([ 1.60943791, 0.69314718]) >>> coo.todense() matrix([[ 1.60943791, 0. , 0. , 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. , 0.69314718, 0. , 0. ]])
Note that this does not work properly if the sparse format has duplicate elements (which is valid in COO format); he will take the logs separately and log(a) + log(b) != log(a + b) . You probably want to convert to CSR or CSC first (which is fast) to avoid this problem.
You will also have to add checks if the sparse matrix is ββin a different format, of course. And if you do not want to change the matrix in place, just create a new sparse matrix in the same way as in your answer, but without adding 3 , because this is completely optional here.