擅长:python、mysql、java
<p>首先,<code>lil</code>你总结的矩阵可能真的很糟糕,我会尝试<code>COO</code>或者{<cd3>}(我不知道哪个更好,但是{<cd1>}对于这些操作中的许多来说可能天生就比较慢,即使切片也可能慢得多,尽管我没有测试)。(除非您知道例如<code>dia</code>非常适合)</p>
<p>基于<code>COO</code>我可以想象做一些欺骗。由于<code>COO</code>有<code>row</code>和{<cd9>}数组来给出确切的位置:</p>
<pre><code>matrix = A.tocoo()
new_row = matrix.row // 5
new_col = matrix.col // 5
bin = (matrix.shape[0] // 5) * new_col + new_row
# Now do a little dance because this is sparse,
# and most of the possible bin should not be in new_row/new_col
# also need to group the bins:
unique, bin = np.unique(bin, return_inverse=True)
sum = np.bincount(bin, weights=matrix.data)
new_col = unique // (matrix.shape[0] // 5)
new_row = unique - new_col * (matrix.shape[0] // 5)
result = scipy.sparse.coo_matrix((sum, (new_row, new_col)))
</code></pre>
<p>(我不能保证我没有混淆行和列,这只适用于方阵…)</p>