How to convert data.frame into matrix based on two columns in data.frame [duplicate]

陌路散爱 提交于 2021-01-27 12:34:26

问题


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

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

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)



回答1:


You can use DataFrame.pivot for this:

df_pivot = df.pivot(index='userId', columns='movieId', values='rating')

[out]

print(df_pivot)

movieId  1    32   47   50   110
userId                          
12882    4.0  3.5  5.0  5.0  4.5


来源:https://stackoverflow.com/questions/55764520/how-to-convert-data-frame-into-matrix-based-on-two-columns-in-data-frame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!