"电影类型"数据集中的"类型"列每行中有多个类别.如何将所有类别彼此分开?



这是代码:

data[['Movies','Genre']

输出如下所示:

Movies Genre
1    Xyz   Drama,Action
2    Abc   Horror,Thriller
3    Mnb   Action,Thriller

所需的输出为:

Movies Genre
1    Xyz   Drama
2    Xyz   Action
3    Abc   Horror
4    Abc   Thriller
5    Mnb   Action
6    Mnb   Thriller

如果我这样做:data["Genre"]max()它应该给出:Action, Thriller

首先,您需要将Genrestr转换为list; 其次,使用pandas.DataFrame.explode将类似列表的每个元素转换为行

>>> df["Genre"] = df["Genre"].str.split(",")
>>> df
Movies               Genre
0    Xyz     [Drama, Action]
1    Abc  [Horror, Thriller]
2    Mnb  [Action, Thriller]
>>> df.explode("Genre")
Movies     Genre
0    Xyz     Drama
0    Xyz    Action
1    Abc    Horror
1    Abc  Thriller
2    Mnb    Action
2    Mnb  Thriller

相关内容

最新更新