【问题标题】:Find unique words in a python dataframe column and count them在 python 数据框列中查找唯一单词并计算它们
【发布时间】:2021-10-24 01:25:41
【问题描述】:

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

尝试用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

【问题讨论】:

    标签: python pandas dataframe counter frequency


    【解决方案1】:

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

    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})
    

    【讨论】:

    • 集合代码有效。我进一步将字典转换为系列/数据框。谢谢你。这非常有用。
    【解决方案2】:

    我们可以str.splitexplode然后使用value_counts:

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

    或者str.get_dummiessumsort_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
    

    【讨论】:

    • 出现错误。 “'系列'对象没有属性'爆炸'。试图解决它。
    • 0.25.0(2019 年 7 月 18 日)以来,该系列已经爆炸式增长
    猜你喜欢
    • 2020-07-04
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多