从pandas datafram中提取并计算每行的唯一hashtags

2024-06-25 22:47:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pandas数据帧df,有一个字符串列Posts,类似于:

df['Posts']
0       "This is an example #tag1"
1       "This too is an example #tag1 #tag2"
2       "Yup, still an example #tag1 #tag1 #tag3"

当我试图用下面的代码计算

^{pr2}$

我明白了

#tag1             4
#tag2             1
#tag3             1

但我需要的结果是每行唯一的hashtags计数,如下所示:

#tag1             3
#tag2             1
#tag3             1

Tags: 数据字符串anpandasdfisexamplethis
2条回答

这是一个使用itertools.chaincollections.Counter的解决方案:

import pandas as pd
from collections import Counter
from itertools import chain

s = pd.Series(['This is an example #tag1',
               'This too is an example #tag1 #tag2',
               'Yup, still an example #tag1 #tag1 #tag3'])

tags = s.map(lambda x: {i[1:] for i in x.split() if i.startswith('#')})

res = Counter(chain.from_iterable(tags))

print(res)

Counter({'tag1': 3, 'tag2': 1, 'tag3': 1})

绩效基准

对于大型系列,collections.Counter的速度是pd.Series.str.extractall的2倍:

^{pr2}$

使用drop_duplicates删除每个帖子中的重复标记,然后可以使用value_counts

df.Posts.str.extractall(
    r'(\#\w+)'
).reset_index().drop_duplicates(['level_0', 0])[0].value_counts()

更短的备选方案,其中level=0被传递给reset_index

^{pr2}$

两者都将输出:

#tag1    3
#tag3    1
#tag2    1
Name: 0, dtype: int64

相关问题 更多 >