Coming into this rather late, but for those seeking a method for indexing into elements of a scipy sparse csr or csc matrix, we can convert the nonzero row, column, and data arrays into a pandas dataframe and extract the element from the data attribute of the matrix. This simple technique doesn't require conversion to a dense array.
Let's create sparse array.
import numpy as np
import pandas as pd
from scipy import stats
from scipy.sparse import csr_matrix, random
from numpy.random import default_rng
rng = default_rng()
rvs = stats.poisson(25, loc=10).rvs
A = random(5, 5, density=0.25, random_state=rng, data_rvs=rvs)
A.A
Output
array([[32., 0., 32., 0., 0.],
[ 0., 29., 0., 0., 0.],
[ 0., 0., 0., 30., 0.],
[ 0., 0., 37., 30., 0.],
[ 0., 0., 0., 0., 0.]])
The following function takes a sparse csr or csc matrix, as well as the desired nonzero row, and column indices.
def get_element(matrix, row, col):
rows, cols = matrix.nonzero()
d = {"row": rows, "col": cols, "data": matrix.data}
df = pd.DataFrame(data=d)
element = df[(df["row"] == row) & (df["col"] == col)]["data"].values[0]
return element
To index into A[3,2]:
get_element(A, row=3,col=2)
Output:
37.0