【问题标题】:Extract and count hashtags from a dataframe从数据框中提取和计算主题标签
【发布时间】:2021-06-13 05:55:47
【问题描述】:

我有一个包含一些推文的数据框,如下所示:

tweets = pd.Series(['This is a tweet example #help #thankyou', 
                    'Second tweet example #help', 
                    'Third tweet example #help #stackoverflow'])

tweets_df = pd.DataFrame({'Tweets': tweets})

然后我将主题标签放在数据框的另一列中

tweets_df['hashtags'] = tweets_df['Tweets'].apply(lambda twt : re.findall(r"#(\w+)", twt))

现在我想计算它们并将结果放入另一个数据框中。我尝试了以下方法,但没有成功

tweets_df['hashtags'].str.split(expand=True).stack().value_counts()

结果必须是这样的:

#help           2
#thankyou       1
#stackoverflow  1

【问题讨论】:

  • 不应该#help3

标签: python-3.x pandas


【解决方案1】:

让我们使用extractallvalue_counts

tweets_df.Tweets.str.extractall(r'(\#\w+)')[0].value_counts()

输出:

#help             3
#stackoverflow    1
#thankyou         1
Name: 0, dtype: int64

【讨论】:

    【解决方案2】:

    您可以使用Counter

    from collections import Counter
    d = Counter(tweets_df.hashtags.sum())
    df = pd.DataFrame([d]).T
    
    >>> df
                    0
    help            3
    stackoverflow   1
    thankyou        1 
    

    【讨论】:

      【解决方案3】:

      您不需要将tweets 制作成数据框。只需从那里执行提取:

      tweets.str.extractall(r'(\#\w*)')[0].value_counts()
      
      #help             3
      #stackoverflow    1
      #thankyou         1
      Name: 0, dtype: int64
      

      【讨论】:

        猜你喜欢
        • 2018-11-07
        • 2018-02-03
        • 2016-06-20
        • 2017-04-12
        • 1970-01-01
        • 2015-01-15
        • 2020-03-16
        • 2020-02-17
        • 1970-01-01
        相关资源
        最近更新 更多