格式字典从与行/列的坐标矩阵到原始ID



我有一个带有列user_idproduct_codescore的Pandas DataFrame,然后将其转换为COO_MATRIX。每行代表user_id,每个列A product_code。由于稀疏的形成,矩阵中的值是得分或NAN值。我必须使用稀疏的矩阵,因为内存有效并且数据集很大。

使用user_idproduct_code映射row/columns的最快方法?

我目前正在为用户使用此功能,而对产品则相同,而不是.row,我使用.col

def user_row_dictionary(df, coo_matrix):
    row_to_user_id= dict()
    inter = np.array(df['user_id'])
    for i in range(len(coo_matrix.row)):
        row_to_user_id[coo_matrix.row[i]] = inter[i]
    user_id_to_row = { v: k for k, v in row_to_user_id.items() }
    return row_to_user_id, user_id_to_row

该功能效果很好,但我想要一种更快的方法。

文档没有为此提供标准功能。

有什么想法?

看起来您只是将row的元素与inter的元素一对一配对。您可以用一个语句构造这样的词典:

In [45]: inter = np.array(['one', 'two', 'three', 'four'])
In [46]: row = np.array([0,1,2,3])
In [47]: dict(zip(row, inter))
Out[47]: {0: 'one', 1: 'two', 2: 'three', 3: 'four'}
In [48]: dict(zip(inter, row))
Out[48]: {'four': 3, 'one': 0, 'three': 2, 'two': 1}

最新更新