将 Pandas DataFrame 转换为稀疏矩阵 [英] Converting Pandas DataFrame to sparse matrix

查看:163
本文介绍了将 Pandas DataFrame 转换为稀疏矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

data=pd.get_dummies(data['movie_id']).groupby(data['user_id']).apply(max)

df=pd.DataFrame(data)

replace=df.replace(0,np.NaN)

t=replace.fillna(-1)

sparse=sp.csr_matrix(t.values)

我的数据由两列组成:movie_id 和 user_id.

My data consist of two columns which are movie_id and user_id.

 user_id      movie_id

   5             1000 

   6             1007 

我想将数据转换为稀疏矩阵.我首先创建了一个交互矩阵,其中行表示 user_id,列表示 movie_id,正交互为 +1,负交互为 -1.然后我使用 scipy 将其转换为稀疏矩阵.我的结果是这样的:

I want to convert the data to a sparse matrix. I first created an interaction matrix where rows indicate user_id and columns indicate movie_id with positive interaction as +1 and negative interaction as -1. Then I converted it to a sparse matrix using scipy. My result looks like this:

(0,0) -1

(0,1) -1

(0,2) 1

但实际上我想要的是:

(1000,0) -1

(1000,0) -1

(1000,1) 1

(1007,0) -1

(1007,0) -1

任何帮助将不胜感激.

推荐答案

如果你有行和列索引(在你的例子中分别是 movie_iduser_id),建议使用COO格式创建.

If you have both the row and column index (in your case movie_id and user_id, respectively), it is advisable to use the COO format for creation.

您可以将其转换为稀疏格式,如下所示:

You can convert it into a sparse format like so:

import scipy
sparse_mat = scipy.sparse.coo_matrix((t.values, (df.movie_id, df.user_id)))

重要的是,请注意构造函数如何通过将电影 ID 和用户 ID 作为数据参数传递来给出稀疏矩阵的隐式形状.
此外,您可以将此矩阵转换为您想要的任何其他稀疏格式,例如 CSR.

Importantly, note how the constructor gives the implicit shape of the sparse matrix by passing both the movie ID and user ID as arguments for the data.
Furthermore, you can convert this matrix to any other sparse format you desire, as for example CSR.

这篇关于将 Pandas DataFrame 转换为稀疏矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆