Skip to main content
 首页 » 编程设计

python之如何创建虚拟变量然后使用 scikit-learn 进行聚合

2025年05月04日12JustinYoung

我知道用pandas这个包可以很容易的实现,但是因为它太稀疏太大了(170,000 x 5000),最后又需要用sklearn重新处理数据,不知道是不是有一种方法可以使用 sklearn。我尝试了一个热编码器,但无法将假人与“id”相关联。

df = pd.DataFrame({'id': [1, 1, 2, 2, 3, 3], 'item': ['a', 'a', 'c', 'b', 'a', 'b']}) 
 
   id item 
0   1    a 
1   1    a 
2   2    c 
3   2    b 
4   3    a 
5   3    b 
 
dummy = pd.get_dummies(df, prefix='item', columns=['item']) 
dummy.groupby('id').sum().reset_index() 
 
   id  item_a  item_b  item_c 
0   1       2       0       0 
1   2       0       1       1 
2   3       1       1       0 

更新:

现在我来了,id丢了,怎么聚合呢?

lab = sklearn.preprocessing.LabelEncoder() 
labels = lab.fit_transform(np.array(df.item)) 
enc = sklearn.preprocessing.OneHotEncoder() 
dummy = enc.fit_transform(labels.reshape(-1,1)) 
 
dummy.todense() 
 
matrix([[ 1.,  0.,  0.], 
        [ 1.,  0.,  0.], 
        [ 0.,  0.,  1.], 
        [ 0.,  1.,  0.], 
        [ 1.,  0.,  0.], 
        [ 0.,  1.,  0.]]) 

请您参考如下方法:

以防将来有人需要引用,我把我的解决方案放在这里。 我使用了 scipy 稀疏矩阵。

首先进行分组,统计记录数。

df = df.groupby(['id','item']).size().reset_index().rename(columns={0:'count'}) 

这需要一些时间而不是几天。

然后使用数据透视表,我找到了一个解决方案here .

from scipy.sparse import csr_matrix 
 
def to_sparse_pivot(df, id, item, count): 
    id_u = list(df[id].unique()) 
    item_u = list(np.sort(df[item].unique())) 
    data = df[count].tolist() 
    row = df[id].astype('category', categories=id_u).cat.codes 
    col = df[item].astype('category', categories=item_u).cat.codes 
    return csr_matrix((data, (row, col)), shape=(len(id_u), len(item_u))) 

然后调用函数

result = to_sparse_pivot(df, 'id', 'item', 'count')