【问题标题】:How to get the count of occurence of a list of keywords on a datacolumn in a dataframe in python如何获取python数据框中数据列上关键字列表的出现次数
【发布时间】:2017-07-25 05:21:58
【问题描述】:
 my_list=["one","is"]

 df
 Out[6]:
        Name    Story
   0    Kumar   Kumar is one of the great player in his team
   1    Ravi    Ravi is a good poet
   2    Ram     Ram drives well

如果 my_list 中的任何项目出现在“故事”列中,我需要获取所有项目的出现次数。

 my_desired_output

 new_df
 word     count
 one       1
 is        2

我实现了提取包含 my_list 中任何项目的行

mask=df1["Story"].str.contains('|'.join(my_list),na=False) but now I am trying get the counts of each word in my_list

【问题讨论】:

    标签: python pandas dataframe data-analysis


    【解决方案1】:

    您可以将str.splitstack 一起用于Series 的单词:

    a = df['Story'].str.split(expand=True).stack()
    print (a)
    0  0     Kumar
       1        is
       2       one
       3        of
       4       the
       5     great
       6    player
       7        in
       8       his
       9      team
    1  0      Ravi
       1        is
       2         a
       3      good
       4      poet
    2  0       Ram
       1    drives
       2      well
    dtype: object
    

    然后通过boolean indexingisin 过滤,得到value_counts 并为DataFrame 添加rename_axisreset_index

    df = a[a.isin(my_list)].value_counts().rename_axis('word').reset_index(name='count')
    print (df)
      word  count
    0   is      2
    1  one      1
    

    另一种解决方案是通过str.split 创建所有单词列表,然后通过from_iterable 填充,使用Counter,最后通过构造函数创建DataFrame

    from collections import Counter
    from  itertools import chain
    
    my_list=["one","is"]
    
    a = list(chain.from_iterable(df['Story'].str.split().values.tolist()))
    print (a)
    ['Kumar', 'is', 'one', 'of', 'the', 'great', 'player', 
     'in', 'his', 'team', 'Ravi', 'is', 'a', 'good', 'poet', 'Ram', 'drives', 'well']
    
    b = Counter([x for x in a if x in my_list])
    print (b)
    Counter({'is': 2, 'one': 1})
    
    df = pd.DataFrame({'word':list(b.keys()),'count':list(b.values())}, columns=['word','count'])
    print (df)
      word  count
    0  one      1
    1   is      2
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-03
    • 1970-01-01
    • 2023-01-23
    • 2015-09-09
    • 2018-12-29
    • 1970-01-01
    • 2019-08-14
    • 2023-01-12
    相关资源
    最近更新 更多