栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

设置csr_matrix的行

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

设置csr_matrix的行

最后,我设法通过索引处理来完成此任务。

def set_row_csr(A, row_idx, new_row):    '''    Replace a row in a CSR sparse matrix A.    Parameters    ----------    A: csr_matrix        Matrix to change    row_idx: int        index of the row to be changed    new_row: np.array        list of new values for the row of A    Returns    -------    None (the matrix A is changed in place)    Prerequisites    -------------    The row index shall be smaller than the number of rows in A    The number of elements in new row must be equal to the number of columns in matrix A    '''    assert sparse.isspmatrix_csr(A), 'A shall be a csr_matrix'    assert row_idx < A.shape[0],  'The row index ({0}) shall be smaller than the number of rows in A ({1})'  .format(row_idx, A.shape[0])    try:        N_elements_new_row = len(new_row)    except TypeError:        msg = 'Argument new_row shall be a list or numpy array, is now a {0}'        .format(type(new_row))        raise AssertionError(msg)    N_cols = A.shape[1]    assert N_cols == N_elements_new_row,  'The number of elements in new row ({0}) must be equal to '  'the number of columns in matrix A ({1})'  .format(N_elements_new_row, N_cols)    idx_start_row = A.indptr[row_idx]    idx_end_row = A.indptr[row_idx + 1]    additional_nnz = N_cols - (idx_end_row - idx_start_row)    A.data = np.r_[A.data[:idx_start_row], new_row, A.data[idx_end_row:]]    A.indices = np.r_[A.indices[:idx_start_row], np.arange(N_cols), A.indices[idx_end_row:]]    A.indptr = np.r_[A.indptr[:row_idx + 1], A.indptr[(row_idx + 1):] + additional_nnz]


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/661301.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号