How to list, in a simple and one line code (and fast!), all non zero elements of a csr_matrix
?
I'm using this code:
edges_list = list([tuple(row) for row in np.transpose(A.nonzero())])
weight_list = [A[e] for e in edges_list]
but it is taking quite a long time to execute.
For a CSR matrix in canonical form, access the data array directly:
A.data
but be aware that matrices not in canonical form may include explicit zeros or duplicate entries in their representation, which will need special handling. For example,
# Merge duplicates and remove explicit zeros. Both operations modify A.
# We sum duplicates first because they might sum to zero - for example,
# if a 5 and a -5 are in the same spot, we have to sum them to 0 and then remove the 0.
A.sum_duplicates()
A.eliminate_zeros()
# Now use A.data
do_whatever_with(A.data)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With