def tocoo(self, copy=False): from .coo import coo_matrix if self.nnz == 0: return coo_matrix(self.shape, dtype=self.dtype) idx_dtype = get_index_dtype(maxval=max(self.shape)) data = np.fromiter(itervalues(self), dtype=self.dtype, count=self.nnz) row = np.fromiter((i for i, _ in iterkeys(self)), dtype=idx_dtype, count=self.nnz) col = np.fromiter((j for _, j in iterkeys(self)), dtype=idx_dtype, count=self.nnz) A = coo_matrix((data, (row, col)), shape=self.shape, dtype=self.dtype) A.has_canonical_format = True return A
def count_nonzero(self): return sum(x != 0 for x in itervalues(self))