从头开始使用 unary/binary 数据创建 csr_matrix

Creating a csr_matrix with unary/binary data from the start

我从 SQL 中的 pandas 数据帧中导入二进制数据,该数据帧由 UserIdItemId 列组成。我正在使用 implicit/binary 数据,您可以在下面的 pivot_table 中看到。

Dummy data

frame=pd.DataFrame()
frame['Id']=[2134, 23454, 5654, 68768]
frame['ItemId']=[123, 456, 789, 101]

我知道如何在 Pandas 中创建 pivot_table 使用:

print(frame.groupby(['Id', 'ItemId'], sort=False).size().unstack(fill_value=0))

ItemId  123  456  789  101
Id
2134      1    0    0    0
23454     0    1    0    0
5654      0    0    1    0
68768     0    0    0    1

并将其转换为 SciPy csr_matrix,但我想从一开始就创建一个稀疏矩阵,而不必从 Pandas df 转换。这样做的原因是我得到一个错误:Unstacked DataFrame is too big, causing int32 overflow,因为我的原始数据由 378.777 行组成。

非常感谢任何帮助!

我正在尝试做与这些答案相同的事情

但是我还没有 frame['count'] 数据。

使用4th option实例化矩阵:

Id = [2134, 23454, 5654, 68768]
ItemId = [123, 456, 789, 101]

csrm = csr_matrix(([1]*len(Id), (Id,ItemId)))

结果:

<68769x790 sparse matrix of type '<class 'numpy.int32'>'
    with 4 stored elements in Compressed Sparse Row format>

我假设您可以以某种方式将数据值行读入内存中的单独列表,即,就像您在示例中所做的那样(具有 IdItemId 的列表) .根据您对 post 的评论,我们也不希望出现重复。请注意,以下 将不起作用 ,如果您有重复项!

所提供的解决方案还引入了一个(稀疏)矩阵,它不像示例中所示那样密集,因为我们将直接使用 Id 值作为 matrix/row 个条目。

要将它们传递给构造函数,如果您正在查看 SciPy documentation:

csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)])

where data, row_ind and col_ind satisfy the relationship a[row_ind[k], col_ind[k]] = data[k].

意思是我们可以直接将列表作为索引传递给我们的稀疏矩阵,如下所示:

from scipy.sparse import csr_matrix
Id_values = load_values() # gets the list of entries as in the post example
ItemId_values = load_more_values()

sparse_mat = csr_matrix(([1]*len(Id_values), # entries will be filled with ones
                        (Id_values, ItemId_values)), # at those positions
                        shape=(max(Id_values)+1, max(ItemId_values)+1)) # shape is the respective maximum entry of each dimension

请注意,这不会给您任何排序,而是将值放在它们各自的 Id 位置,即第一对将保存在位置 (2134, 134) 而不是 (0, 0)