计算熊猫中字符串中单词的出现次数

时间:2020-09-23 06:58:26

标签: python pandas string count

我试图计算一个单词在熊猫系列的所有弦中出现的次数 我有一个遵循以下逻辑的数据框df

word

hi    
hello
bye
goodbye

还有一个看起来像这样的df_2(向右滚动以查看另一列)

sentence                                                                            metric_x

hello, what a wonderful day                                                         10
I did not said hello today                                                          15
what comes first, hi or hello                                                       25
the most used word is hi                                                            30
hi or hello, which is more formal                                                   50
he said goodbye, even though he never said hi or hello in the first place           5

我正在尝试在df中实现以下目标:计算word存在的次数以及与metric_x相匹配的值的word

word        count       metric_x_sum
        
hi          4           110
hello       5           105
bye         0           0
goodbye     1           5

我正在使用这个:

df['count'] = df['word'].apply(lambda x: df_2['sentence'].str.count(x).sum())

问题出在数据帧的长度上,我在70,000中有df个唯一词,在250,000中有df_2个唯一句子,上面的行运行了15分钟,我不知道它可以运行多长时间。

运行15分钟后,出现此错误:

error: multiple repeat at position 2

有没有更聪明,更快捷的方法来实现这一目标?

1 个答案:

答案 0 :(得分:1)

首先将单词和DataFrame.explode分开,然后用Series.str.strip删除尾随值,

df2 = df_2.assign(word = df_2['sentence'].str.split()).explode('word')
df2['word'] = df2['word'].str.strip(',')
#print (df2)

然后DataFrame.merge使用左连接并聚合GroupBy.count,以排除sum的缺失值:

df3 = (df.merge(df2, on='word', how='left')
         .groupby('word')
         .agg(count=('metric_x', 'count'), metric_x_sum=('metric_x','sum')))
# print (df3)

最后添加到原始照片:

df = df.join(df3, on='word')
df['metric_x_sum'] = df['metric_x_sum'].astype(int)
print (df)
      word  count  metric_x_sum
0       hi      4           110
1    hello      5           105
2      bye      0             0
3  goodbye      1             5