首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >每天提到一个词

每天提到一个词
EN

Stack Overflow用户
提问于 2018-12-17 10:49:49
回答 3查看 94关注 0票数 3

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

代码语言:javascript
复制
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...

(...)

我想计算“苹果”这个词的每日提到的总数--因此按日期进行汇总。如何创建"final_df"?

代码语言:javascript
复制
print(final_df) 

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

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-12-17 11:21:13

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

代码语言:javascript
复制
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
票数 3
EN

Stack Overflow用户

发布于 2018-12-17 11:19:38

您可以对不同的日期进行GroupBy,使用str.count来计数Apple的出现情况,并使用sum进行聚合,以获取每个组中的计数数量:

代码语言:javascript
复制
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
票数 1
EN

Stack Overflow用户

发布于 2018-12-17 11:23:14

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

代码语言:javascript
复制
>>> 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

解决办法:

代码语言:javascript
复制
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()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53813632

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档