从pandas数据框中提取并计算每行唯一的hashtag数量

3

我有一个带有字符串列Posts的pandas数据框df,形式如下:

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

当我尝试使用以下代码计算hashtag数量时:
count_hashtags = df['Posts'].str.extractall(r'(\#\w+)')[0].value_counts()

我明白了,

#tag1             4
#tag2             1
#tag3             1

但是我需要每行唯一的hashtag数量统计结果,就像这样:
#tag1             3
#tag2             1
#tag3             1
2个回答

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倍:

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'])

def hal(s):
    return s.str.extractall(r'(\#\w+)')\
            .reset_index(level=0)\
            .drop_duplicates()[0]\
            .value_counts()

def jp(s):
    tags = s.map(lambda x: {i[1:] for i in x.split() if i.startswith('#')})
    return Counter(chain.from_iterable(tags))

s = pd.concat([s]*100000, ignore_index=True)

%timeit hal(s)  # 2.76 s per loop
%timeit jp(s)   # 1.25 s per loop

2

使用drop_duplicates来去除每篇文章中的重复标签,然后您可以使用value_counts

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

可以通过将reset_index方法的参数level设置为0来缩短代码。

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

两者都会输出:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接