繁体   English   中英

在 python dataframe 列中找到唯一的单词并计算它们

[英]Find unique words in a python dataframe column and count them

我试图找到唯一的单词数量以及它们重复了多少次。

尝试在 python 中编写相同的代码。

输入数据集:

电影 类型
电影 1 动作/动画/科幻
电影 2 冒险/动画/剧情/悬疑/科幻

output 数据集:

类型 数数
科幻 2个
Animation 2个
行动 1个
冒险 1个
戏剧 1个
神秘 1个

collections.Counter()是你的朋友。 您可以使用DataFrame构造函数将生成的字典转换为 dataframe。

import pandas as pd
import collections

df = pd.DataFrame(
    [
        ["movie 1", "Action/Animation/Sci-Fi"],
        ["movie 2", "Adventure/Animation/Drama/Mystery/Sci-Fi"],
    ],
    columns=["Movie", "Genre"],
)

ctr = collections.Counter()
for r in df["Genre"]:
    ctr.update(r.split("/"))
print(ctr)

# output: Counter({'Animation': 2, 'Sci-Fi': 2, 'Action': 1, 'Adventure': 1, 'Drama': 1, 'Mystery': 1})

我们可以str.split explode然后使用value_counts

out = (
    df['genre'].str.split('/')
        .explode()
        .value_counts()
        .rename_axis('Genre')
        .reset_index(name='count')
)

或者str.get_dummies sum sort_values

out = (
    df['genre'].str.get_dummies('/').sum()
        .rename('Genre')
        .reset_index(name='count')
        .sort_values('count', ascending=False, ignore_index=True)
)

out

       Genre  count
0  Animation      2
1     Sci-Fi      2
2     Action      1
3  Adventure      1
4      Drama      1
5    Mystery      1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM