从数据框

时间:2018-04-16 20:31:22

标签: python-3.x pandas

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

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

3 个答案:

答案 0 :(得分:2)

让我们使用extractallvalue_counts

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

输出:

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

答案 1 :(得分:0)

您可以使用Counter

from collections import Counter
d = Counter(tweets_df.hashtags.sum())
df = pd.DataFrame([d]).T

>>> df
                0
help            3
stackoverflow   1
thankyou        1 

答案 2 :(得分:0)

您无需将tweets放入数据框中。只需从那里执行提取:

tweets.str.extractall(r'(\#\w*)')[0].value_counts()

#help             3
#stackoverflow    1
#thankyou         1
Name: 0, dtype: int64
相关问题