我不知道任何既定的良好做法,所以这里有一个相当直接的 coo_matrix 重塑函数。它将其参数转换为 coo_matrix,因此它将实际适用于其他稀疏格式(但它返回一个 coo_matrix)。
from scipy.sparse import coo_matrix
def reshape(a, shape):
"""Reshape the sparse matrix `a`.
Returns a coo_matrix with shape `shape`.
"""
if not hasattr(shape, '__len__') or len(shape) != 2:
raise ValueError('`shape` must be a sequence of two integers')
c = a.tocoo()
nrows, ncols = c.shape
size = nrows * ncols
new_size = shape[0] * shape[1]
if new_size != size:
raise ValueError('total size of new array must be unchanged')
flat_indices = ncols * c.row + c.col
new_row, new_col = divmod(flat_indices, shape[1])
b = coo_matrix((c.data, (new_row, new_col)), shape=shape)
return b
例子:
In [43]: a = coo_matrix([[0,10,0,0],[0,0,0,0],[0,20,30,40]])
In [44]: a.A
Out[44]:
array([[ 0, 10, 0, 0],
[ 0, 0, 0, 0],
[ 0, 20, 30, 40]])
In [45]: b = reshape(a, (2,6))
In [46]: b.A
Out[46]:
array([[ 0, 10, 0, 0, 0, 0],
[ 0, 0, 0, 20, 30, 40]])
现在,我敢肯定这里有几个定期贡献者可以提出更好的东西(更快,更高效的内存,更少的填充...... :)