Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按|拆分,并在熊猫系列中找到唯一值_Python_Pandas - Fatal编程技术网

Python 按|拆分,并在熊猫系列中找到唯一值

Python 按|拆分,并在熊猫系列中找到唯一值,python,pandas,Python,Pandas,我有一个来自movielens数据集的电影数据,我想从“类型”列中选择唯一的类型。这是数据集 结果是这样的 有人能帮我从“流派”列中拆分和选择独特的流派吗 谢谢解决方案: 输出: 说明: 这一部分将列体裁的体裁拆分为每种体裁一列。输出为摘录: df["genres"].str.split("|", expand=True) 0 1 2 0 Adventure Animation C

我有一个来自movielens数据集的电影数据,我想从“类型”列中选择唯一的类型。这是数据集

结果是这样的

有人能帮我从“流派”列中拆分和选择独特的流派吗

谢谢

解决方案:

输出:

说明:

这一部分将列体裁的体裁拆分为每种体裁一列。输出为摘录:

df["genres"].str.split("|", expand=True)

    0           1           2       
0   Adventure   Animation   Children
1   Adventure   Children    Fantasy
2   Comedy      None        None 
.stack将所有列堆叠为一个:

df["genres"].str.split("|", expand=True).stack()

0    Adventure
1    Animation
2     Children
3       Comedy
4      Fantasy
然后,pd.unique返回一个数组,其中包含序列的唯一值。

解决方案:

输出:

说明:

这一部分将列体裁的体裁拆分为每种体裁一列。输出为摘录:

df["genres"].str.split("|", expand=True)

    0           1           2       
0   Adventure   Animation   Children
1   Adventure   Children    Fantasy
2   Comedy      None        None 
.stack将所有列堆叠为一个:

df["genres"].str.split("|", expand=True).stack()

0    Adventure
1    Animation
2     Children
3       Comedy
4      Fantasy

然后,pd.unique返回一个数组,其中包含序列的唯一值。

您可以将数据集的“流派”列转入列表,然后循环将每个流派添加到更广泛的列表中

genres = []
for mixed_genres in data.genres.to_list(): 
   genres.extend(mixed_genres.split("|"))
然后使用set仅提取唯一值

unique_genres = list(set(genres))
最后将其转换回列,使其看起来与所需的输出完全相同

pd.DataFrame(unique_genres,columns=["genres"])

您可以将数据集的“流派”列转换为列表,然后循环将每个流派添加到更广泛的列表中

genres = []
for mixed_genres in data.genres.to_list(): 
   genres.extend(mixed_genres.split("|"))
然后使用set仅提取唯一值

unique_genres = list(set(genres))
最后将其转换回列,使其看起来与所需的输出完全相同

pd.DataFrame(unique_genres,columns=["genres"])

它起作用了。非常感谢你的工作。非常感谢你