scipy.sparse
矩阵,需要迭代每一行以检索非零元素的索引和值。我已经阅读过有关
有效迭代 CSR 矩阵的方法,但我尚未成功修改它们以满足我的要求。
这是我目前正在做的事情:
#'matrix' is a scipy.sparse.csr_matrix
for index in tqdm(range(matrix.shape[0]), desc="Updating values", leave=False):
row = matrix.getrow(index)
values_indices = row.indices
# Further processing...
有没有更有效的方法来实现这一目标?
初始方法(使用 getrow):
# 'csr_matrix' is a scipy.sparse.csr_matrix
for user_index in range(csr_matrix.shape[0]):
row = csr_matrix.getrow(user_index)
values_indices = row.indices
对于 10,000 行和 5,000 列的矩阵,此方法花费了 2.9309 秒。我基于
this的第二种方法:
start_time = time.time()
old_i = None
indices = []
values = []
for i, j, v in zip(coo_matrix.row, coo_matrix.col, coo_matrix.data):
if i != old_i:
if old_i is not None:
other_method(indices, values)
indices = [j]
values = [v]
else:
indices.append(j)
values.append(v)
old_i = i
# Handle the last group
if indices and values:
other_method(indices, values)
end_time = time.time()
对于相同的矩阵大小,此方法仅花费 0.0030 秒。但是,我不确定它们都是最佳实践。