如何根据data.frame中的两列将data.frame转换为矩阵 [英] How to convert data.frame into matrix based on two columns in data.frame
本文介绍了如何根据data.frame中的两列将data.frame转换为矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框看起来像
I have a data frame looks like
userId movieId rating
0 12882 1 4.0
1 12882 32 3.5
2 12882 47 5.0
3 12882 50 5.0
4 12882 110 4.5
但是我想把它转换成一个矩阵,行名是userId,列名是movieId,值是评分.
But I want to convert it into a matrix which the rowname is userId, column name is movieId and the value is the rating.
1 32 47
12882 4.0 3.5 5.0
我曾尝试使用 groupby,但在那之后,我不知道如何转换它.
I have try to use the groupby, but after that, I have no idea how to convert it.
test = Ratings[['userId','movieId','rating']]
test_group = test.groupby(['userId','movieId'],as_index=False,sort=False)
推荐答案
您可以使用 DataFrame.pivot
为此:
You can use DataFrame.pivot
for this:
df_pivot = df.pivot(index='userId', columns='movieId', values='rating')
[出]
print(df_pivot)
movieId 1 32 47 50 110
userId
12882 4.0 3.5 5.0 5.0 4.5
这篇关于如何根据data.frame中的两列将data.frame转换为矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文