+5 votes
in Programming Languages by (77.2k points)

I want to find the index of the smallest element in each row and column of a CSR matrix. What function should I use?

1 Answer

+2 votes
by (354k points)
selected by
 
Best answer

The argmin() function of csr_matrix can be used to find the index of the smallest element in each row and column of a CSR matrix. You need to use the argument "axis" to specify row or column.

axis=0 means "for each column which row has the min value."

axis=1 means "for each row which column has the min value."

Here is an example:

>>> import numpy as np
>>> from scipy.sparse import csr_matrix
>>> row = np.array([0, 0, 1, 2, 2, 2])
>>> col = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 2, 5, 3, 1, 4])
>>> X=csr_matrix((data, (row, col)), shape=(3, 3))
>>> X.toarray()
array([[1, 0, 2],
       [0, 0, 5],
       [3, 1, 4]])
>>> X.argmin(axis=0)
matrix([[1, 0, 0]])
>>> X.argmin(axis=1)
matrix([[1],
        [0],
        [1]])
 
 


...