从pandas数据帧

时间:2018-05-29 10:39:22

标签: python python-3.x pandas counter series

我有一个带有字符串列df的pandas数据帧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"

当我尝试使用以下代码来计算主题标签的数量时,

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

我明白了,

#tag1             4
#tag2             1
#tag3             1

但我需要将结果计算为每行唯一的标签,如下所示:

#tag1             3
#tag2             1
#tag3             1

2 个答案:

答案 0 :(得分:2)

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

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

level=0传递给reset_index

的较短替代方案
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

答案 1 :(得分:1)

这是一个使用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