【问题标题】:Daily Mentions of a Word每日提及一个词
【发布时间】:2019-05-17 17:25:31
【问题描述】:

我有以下 df,包含来自不同来源的每日文章:

print(df)

Date         content

2018-11-01    Apple Inc. AAPL 1.54% reported its fourth cons...
2018-11-01    U.S. stocks climbed Thursday, Apple is a real ...
2018-11-02    GONE are the days when smartphone manufacturer...
2018-11-03    To historians of technology, the story of the ...
2018-11-03    Apple Inc. AAPL 1.54% reported its fourth cons...
2018-11-03    Apple is turning to traditional broadcasting t...

(...)

我想计算“Apple”一词的每日提及次数(因此按日期汇总)的总数。如何创建“final_df”?

print(final_df) 

    2018-11-01    2
    2018-11-02    0
    2018-11-03    2
    (...)

【问题讨论】:

标签: python pandas nlp word-count


【解决方案1】:

count 用于新的Series,按列聚合df['Date']sum

df1 = df['content'].str.count('Apple').groupby(df['Date']).sum().reset_index(name='count')
print (df1)
         Date  count
0  2018-11-01      2
1  2018-11-02      0
2  2018-11-03      2

【讨论】:

    【解决方案2】:

    您可以GroupBy 不同的日期,使用str.count 来统计Apple 的出现次数,并与sum 聚合以获得每个组中的计数:

    df.groupby('Date').apply(lambda x: x.content.str.count('Apple').sum())
                      .reset_index(name='counts')
    
          Date     counts
    0 2018-11-01       2
    1 2018-11-02       0
    2 2018-11-03       2
    

    【讨论】:

    • 感谢您的回答简单易读,但我更喜欢在一行中创建一个数据框,而不是一个系列。谢谢。
    • 不是特别;
    • 修改了答案添加reset_index
    【解决方案3】:

    您可以尝试使用str.containsgroupby 函数的替代解决方案,而无需一直使用sum

    >>> df
             Date                                         content
    0  2018-11-01  Apple Inc. AAPL 1.54% reported its fourth cons
    1  2018-11-01   U.S. stocks climbed Thursday, Apple is a real
    2  2018-11-02  GONE are the days when smartphone manufacturer
    3  2018-11-03   To historians of technology, the story of the
    4  2018-11-03  Apple Inc. AAPL 1.54% reported its fourth cons
    5  2018-11-03  Apple is turning to traditional broadcasting t
    

    解决方案:

    df.content.str.contains("Apple").groupby(df['Date']).count().reset_index(name="count")
    
             Date  count
    0  2018-11-01      2
    1  2018-11-02      1
    2  2018-11-03      3
    
    
    # df["content"].str.contains('Apple',case=True,na=False).groupby(df['Date']).count()
    

    【讨论】:

    • @jezrael,不是故意的,但是我改变了我的答案 :-) 希望你不会介意。
    猜你喜欢
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多