Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List non zero elements from sparse matrix in python

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.

like image 444
Miguel Avatar asked Jan 29 '23 00:01

Miguel


1 Answers

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)
like image 60
user2357112 supports Monica Avatar answered Jan 31 '23 22:01

user2357112 supports Monica