使用分类数据构造稀疏矩阵

Abh*_*kur 6 python numpy scipy sparse-matrix

我有一个看起来像这样的数据:

numpy数组:

[[a, abc],
[b, def],
[c, ghi],
[d, abc],
[a, ghi],
[e, fg],
[f, f76],
[b, f76]]
Run Code Online (Sandbox Code Playgroud)

它就像一个用户项矩阵.我想构造一个形状稀疏的矩阵:number_of_items,num_of_users,如果用户评价/购买了一个项目,则给出1,如果没有,则给出0.因此,对于上面的例子,形状应该是(5,6).这只是一个例子,有成千上万的用户和数千个项目.

目前我正在使用两个for循环.是否有任何更快/ pythonic的方法来实现相同的目标?

期望的输出:

1,0,0,1,0,0
0,1,0,0,0,0
1,0,1,0,0,0
0,0,0,0,1,0
0,1,0,0,0,1
Run Code Online (Sandbox Code Playgroud)

其中rows:abc,def,ghi,fg,f76 和columns:a,b,c,d,e,f

小智 3

最简单的方法是为用户和项目分配整数标签,并将它们用作稀疏矩阵的坐标,例如:

import numpy as np
from scipy import sparse

users, I = np.unique(user_item[:,0], return_inverse=True)
items, J = np.unique(user_item[:,1], return_inverse=True)

points = np.ones(len(user_item), int)
mat = sparse.coo_matrix(points, (I, J))
Run Code Online (Sandbox Code Playgroud)