【问题标题】:Pandas - create a tuple of the most frequent words using groupbyPandas - 使用 groupby 创建最常用词的元组
【发布时间】:2021-12-11 18:19:11
【问题描述】:

我有一个包含列的数据框:语言和单词

df:
      Parts of speech  word
    0 Noun             cat
    1 Noun             water
    2 Noun             cat
    3 verb             draw
    4 verb             draw
    5 adj              slow

我想按词性对排名靠前的单词进行分组(我的期望):

Parts of speech     top 
Noun             {'cat':2,'water':1}
verb             {'draw':2}
adj              {'slow':1}

我使用 groupby 方法并应用它,但我没有得到我需要的东西

df2=df.groupby('Parts of speech')['word'].apply(lambda x : x.value_counts())

如何为每个词性创建一个元组?

【问题讨论】:

    标签: python pandas dataframe group-by apply


    【解决方案1】:

    一种方法是使用.agg + collections.Counter 聚合:

    from collections import Counter
    df2=df.groupby('Parts of speech')['word'].agg(Counter)
    print(df2)
    

    输出

    Parts of speech
    Noun    {'cat': 2, 'water': 1}
    adj                {'slow': 1}
    verb               {'draw': 2}
    Name: word, dtype: object
    

    使用value_counts 的替代方法(注意最后的 to_dict 调用):

    df2 = df.groupby('Parts of speech')['word'].agg(lambda x: x.value_counts().to_dict())
    

    【讨论】:

      猜你喜欢
      • 2016-12-28
      • 2018-11-08
      • 2021-11-06
      • 1970-01-01
      • 2015-07-10
      • 2016-01-16
      • 1970-01-01
      • 2022-10-13
      相关资源
      最近更新 更多