在 python 数据框列中查找唯一单词并计算它们

Find unique words in a python dataframe column and count them

我正在尝试查找唯一的单词数量以及它们重复了多少次。

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

输入数据集:

Movie genre
movie 1 Action/Animation/Sci-Fi
movie 2 Adventure/Animation/Drama/Mystery/Sci-Fi

输出数据集:

Genre count
Sci-Fi 2
Animation 2
Action 1
Adventure 1
Drama 1
Mystery 1

collections.Counter() 是你的朋友。您可以使用 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 and then use value_counts:

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

str.get_dummies sum and 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