将多行数据帧合并为单行

时间:2020-01-30 08:48:42

标签: python-3.x pandas pandas-groupby

我有这个数据框。

   userId  movieId                tag
0       2    60756              funny
1       2    60756    Highly quotable
2       2    60756       will ferrell
3       2    89774       Boxing story
4       2    89774                MMA
5       2    89774          Tom Hardy
6       2   106782              drugs
7       2   106782  Leonardo DiCaprio
8       2   106782    Martin Scorsese
9       7    48516       way too long

我想将标签列与相应的movieId和userId结合使用。

   userId  movieId                tag
0       2    60756              funny|Highly quotable|will ferrell
1       2    89774       Boxing story|MMA|Tom Hardy
2       2   106782              drugs|Leonardo DiCaprio|Martin Scorsese
3       2    5643                fun
4       7    48516       way too long

我已经尝试过此代码,但并未考虑每部电影的userId。

result_df = df.groupby('movieId').agg({'tag': list}).apply(lambda r: '|'.join(r['tag']), axis=1).reset_index()
result_df.columns = ['movieId', 'tag']

0 个答案:

没有答案